Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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!

like image 294
William Hu Avatar asked Aug 23 '16 06:08

William Hu


1 Answers

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.

like image 195
Tan Nguyen Avatar answered Sep 28 '22 02:09

Tan Nguyen