成功登录后,您可以使用自定义标头发送CSRF令牌。
例如,将其放在您的session#create中:
response.headers['X-CSRF-Token'] = form_authenticity_token
提供CSRF令牌的示例登录响应标头:
HTTP/1.1 200 OK
Cache-Control: max-age=0, private, must-revalidate
Connection: Keep-Alive
Content-Length: 35
Content-Type: application/json; charset=utf-8
Date: Mon, 22 Oct 2012 11:39:04 GMT
Etag: "9d719d3b9aabd413c3603e04e8a3933d"
Server: WEBrick/1.3.1 (Ruby/1.9.3/2012-10-12)
Set-Cookie: [cut for readability]
X-Csrf-Token: PbtMPfrszxH6QfRcWJCCyRo7BlxJUPU7HqC2uz2tKGw=
X-Request-Id: 178746992d7aca928c876818fcdd4c96
X-Runtime: 0.169792
X-Ua-Compatible: IE=Edge
该令牌有效,直到您再次登录或(如果您通过API支持此操作,则注销)。您的客户端可以从登录响应标头中提取并存储令牌。然后,每个POST / PUT / DELETE请求都必须使用登录时收到的值来设置X-CSRF-Token标头。
具有CSRF令牌的示例POST标头:
POST /api/report HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate, compress
Content-Type: application/json; charset=utf-8
Cookie: [cut for readability]
Host: localhost:3000
User-Agent: HTTPie/0.3.0
X-CSRF-Token: PbtMPfrszxH6QfRcWJCCyRo7BlxJUPU7HqC2uz2tKGw=
文档:form_authenticity_token