简体   繁体   English

Rails 5 devise_token_auth无法验证CSRF令牌的真实性

[英]Rails 5 devise_token_auth Can't verify CSRF token authenticity

I am working on a Rails 5 api project which is used by mobile client with gem devise_token_auth for authorization. 我正在开发一个Rails 5 api项目,移动客户端使用gem devise_token_auth进行授权。

I am clear about what the warning means. 我清楚警告意味着什么。

1st Question: CSRF protect should be turned OFF for api(JSON/XML)respond , correct? 第一个问题: 对于api(JSON / XML)响应CSRF保护应该关闭,对吗?

I searched some on web it seems CSRF just happens on web application with cookie. 我在网上搜索了一些似乎CSRF恰好发生在带有cookie的web应用程序上。 But i read this from rails api documen t: 但是我从rails api文件中读到了这个:

It's important to remember that XML or JSON requests are also affected >and if you're building an API you should change forgery protection >method in ApplicationController (by default: :exception): 重要的是要记住XML或JSON请求也会受到影响>如果您正在构建API,则应该在ApplicationController中更改伪造保护>方法(默认情况下::: exception):

class ApplicationController < ActionController::Base protect_from_forgery unless: -> { request.format.json? } end

So i still get the warning by adding like this: 所以我仍然通过这样添加警告:

class ApplicationController < ActionController::Base
  protect_from_forgery unless: -> { request.format.json? }
  include DeviseTokenAuth::Concerns::SetUserByToken
end

2nd Question: If API doesn't need CSRF protection, why 第二个问题:如果API不需要CSRF保护,为什么呢

protect_from_forgery unless: -> { request.format.json? }

doesn't work? 不起作用?

Not sure if i understood something wrong. 不确定我是否理解错误。 Thank you! 谢谢!

the code should be: 代码应该是:

protect_from_forgery with: :null_session, if: ->{request.format.json?}

You might have to use null_session for API, it provides an empty session during request but doesn't reset it completely. 您可能必须对API使用null_session ,它在请求期间提供空会话但不会完全重置它。 Used as default if :with option is not specified. 在以下情况下用作默认值:未指定选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM