简体   繁体   中英

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.

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 documen t:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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