Rails 5 devise_token_auth无法验证CSRF令牌的真实性 [英] Rails 5 devise_token_auth Can't verify CSRF token authenticity
问题描述
我正在开发一个Rails 5 api项目,该项目由移动客户端使用gem devise_token_auth
进行授权。
<我清楚警告的意思。
第一个问题: 应关闭api(JSON / XML)响应的CSRF保护,对吗?
我在网上搜索了一些内容,似乎CSRF刚好在带有cookie的Web应用程序上发生。但是我是从 rails api documen t:
$ b $阅读的b
重要的是要记住XML或JSON请求也会受到影响,如果您正在构建API,则应在ApplicationController中更改伪造保护方法(默认情况下::
class ApplicationController< ActionController :: Base
protect_from_forgery除非:-> {request.format.json? }
end
所以我仍然可以通过添加这样的警告:
class ApplicationController< ActionController :: Base
protect_from_forgery除非:-> {request.format.json? }
包括DeviseTokenAuth :: Concerns :: SetUserByToken
end
第二个问题:如果API不需要CSRF保护,为什么
protect_from_forgery除非:-> {request.format.json? }
不起作用?
不知道我是否理解错了。谢谢!
代码应为:
protect_from_forgery包含::null_session,如果:-> {request.format.json?}
您可能必须对API使用 null_session
,它在请求期间提供了一个空会话,但没有完全重置它。如果未指定:with选项,则用作默认值。
I am working on a Rails 5 api project which is used by mobile client with gem devise_token_auth
for authorization.
I am clear about what the warning means.
1st Question: CSRF protect should be turned OFF for api(JSON/XML)respond, correct?
I searched some on web it seems CSRF just happens on web application with cookie. But i read this from rails api document:
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):
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
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. Used as default if :with option is not specified.
这篇关于Rails 5 devise_token_auth无法验证CSRF令牌的真实性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!