Rails 5 devise_token_auth Can't verify CSRF token authenticity
Asked Answered
M

1

6

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!

Madcap answered 23/8, 2016 at 6:11 Comment(0)
I
7

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.

Inclinatory answered 23/8, 2016 at 7:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.