在成功登录后,您可以使用自定义标头发送CSRF令牌。
例如,在sessions#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
protect_from_forgery with: :null_session, :if => Proc.new { |c| c.request.format == 'application/json' }
。 - genkilabsprotect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format =~ %r{application/json} }
- Jimmy Shaw