简体   繁体   中英

How to turn off CSRF-token check when using gem devise_token_auth

I am trying to turn off the CSRF-token check in a Rails app (used as API), since I want to handle authentication with the gem devise_token_auth

I made aware my User.rb model about the new form of authentication:

class User < ActiveRecord::Base
  has_many :trainings

  extend Devise::Models
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  include DeviseTokenAuth::Concerns::User
end

In my controller, I am asking to authenticate:

class Api::V1::TrainingsController < ApplicationController
  before_action :authenticate_user!

I am also using the gem rack-cors to decide who can make request to the Rails api (for the time being everyone)

config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*',
        headers: :any,
        methods: [:get, :post, :patch, :delete, :options],
        expose: ['access-token', 'expiry', 'token-type', 'uid', 'client']
      end
    end

1st question: If I comment out the method protect_from_forgery :

class ApplicationController < ActionController::Base
  include DeviseTokenAuth::Concerns::SetUserByToken

  # protect_from_forgery with :exception

Rails still tries to check the CSRF-token:

Started POST "/api/v1/import" for 46.128.35.112 at 2019-07-23 05:04:32 +0000
2019-07-23T05:04:32.586008+00:00 app[web.1]: I, [2019-07-23T05:04:32.585930 #4]  INFO -- : [dd02c2bc-1367-474a-81a3-f60740e7a661] Processing by Api::V1::TrainingsController#import as JSON
2019-07-23T05:04:32.586079+00:00 app[web.1]: I, [2019-07-23T05:04:32.586010 #4]  INFO -- : [dd02c2bc-1367-474a-81a3-f60740e7a661]   Parameters: {"uid"=>"1", "training"=>{}}
2019-07-23T05:04:32.586319+00:00 app[web.1]: W, [2019-07-23T05:04:32.586199 #4]  WARN -- : [dd02c2bc-1367-474a-81a3-f60740e7a661] Can't verify CSRF token authenticity.
2019-07-23T05:04:32.586567+00:00 app[web.1]: I, [2019-07-23T05:04:32.586508 #4]  INFO -- : [dd02c2bc-1367-474a-81a3-f60740e7a661] Completed 422 Unprocessable Entity in 0ms (ActiveRecord: 0.0ms)
2019-07-23T05:04:32.587644+00:00 app[web.1]: F, [2019-07-23T05:04:32.587566 #4] FATAL -- : [dd02c2bc-1367-474a-81a3-f60740e7a661]
2019-07-23T05:04:32.587718+00:00 app[web.1]: F, [2019-07-23T05:04:32.587648 #4] FATAL -- : [dd02c2bc-1367-474a-81a3-f60740e7a661] ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
2019-07-23T05:04:32.587796+00:00 app[web.1]: F, [2019-07-23T05:04:32.587726 #4] FATAL -- : [dd02c2bc-1367-474a-81a3-f60740e7a661]
2019-07-23T05:04:32.587928+00:00 app[web.1]: F, [2019-07-23T05:04:32.587827 #4] FATAL -- : [dd02c2bc-1367-474a-81a3-f60740e7a661] vendor/bundle/ruby/2.4.0/gems/actionpack-5.2.1/lib/action_controller/metal/request_forgery_protection.rb:211:in `handle_unverified_request'
2019-07-23T05:04:32.587930+00:00 app[web.1]: [dd02c2bc-1367-474a-81a3-f60740e7a661] vendor/bundle/ruby/2.4.0/gems/actionpack-5.2.1/lib/action_controller/metal/request_forgery_protection.rb:243:in `handle_unverified_request'
2019-07-23T05:04:32.587931+00:00 app[web.1]: [dd02c2bc-1367-474a-81a3-f60740e7a661] vendor/bundle/ruby/2.4.0/gems/devise-4.6.2/lib/devise/controllers/helpers.rb:255:in `handle_unverified_request'
2019-07-23T05:04:32.587932+00:00 app[web.1]: [dd02c2bc-1367-474a-81a3-f60740e7a661] vendor/bundle/ruby/2.4.0/gems/actionpack-5.2.1/lib/action_controller/metal/request_forgery_protection.rb:238:in `verify_authenticity_token'

As we can see with the lines:

1) Can't verify CSRF token authenticity
2) vendor/bundle/ruby/2.4.0/gems/actionpack-5.2.1/lib/action_controller/metal/request_forgery_protection.rb:211:in `handle_unverified_request'

I don't understand why this validity checks appear, if I comment out protect_from_forgery

2nd question:

In this thread:

Turn off CSRF token in rails 3

I was told to skip the method verify_authenticity_token

skip_before_action :verify_authenticity_token

In order to disable the CSRF token.

If I do it:

class ApplicationController < ActionController::Base
  include DeviseTokenAuth::Concerns::SetUserByToken

  # protect_from_forgery with :exception

  # protect_from_forgery with: :null_session
  skip_before_action :verify_authenticity_token
end

Now I get following error message:

Started POST "/api/v1/import" for 46.128.35.112 at 2019-07-23 05:25:55 +0000
2019-07-23T05:25:55.567398+00:00 app[web.1]: I, [2019-07-23T05:25:55.567274 #4]  INFO -- : [e1fb4a4e-e61b-4865-b83e-133d96d6b193] Processing by Api::V1::TrainingsController#import as JSON
2019-07-23T05:25:55.567487+00:00 app[web.1]: I, [2019-07-23T05:25:55.567386 #4]  INFO -- : [e1fb4a4e-e61b-4865-b83e-133d96d6b193]   Parameters: {"uid"=>"1", "training"=>{}}
2019-07-23T05:25:55.574153+00:00 app[web.1]: D, [2019-07-23T05:25:55.574055 #4] DEBUG -- : [e1fb4a4e-e61b-4865-b83e-133d96d6b193]   User Load (1.9ms)  SELECT  "users".* FROM "users" WHERE "users"."uid" = $1 LIMIT $2  [["uid", "1"], ["LIMIT", 1]]
2019-07-23T05:25:55.604617+00:00 app[web.1]: I, [2019-07-23T05:25:55.604516 #4]  INFO -- : [e1fb4a4e-e61b-4865-b83e-133d96d6b193] Filter chain halted as :authenticate_user! rendered or redirected
2019-07-23T05:25:55.604774+00:00 app[web.1]: I, [2019-07-23T05:25:55.604708 #4]  INFO -- : [e1fb4a4e-e61b-4865-b83e-133d96d6b193] Completed 401 Unauthorized in 37ms (Views: 0.4ms | ActiveRecord: 18.8ms)

Completed 401 Unauthorized

Which looks better, because now the CSRF token check is not applied, but I have the feeling that I also deactivate the access-token from the gem devise_token_auth

question: Which one is the right approach to disable the CSRF-token check? commenting out protect_from_forgery or adding the skip_before_action :verify_authenticity_token ?

If the right approach is skip_before_action :verify_authenticity_token , why I am not being authenticated if I am passing the access-token ?

This is how I am doing the call:

const rawResponse = await fetch('https://plankorailsfour.herokuapp.com/api/v1/import', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Access-Token': auth.accessToken,
      'token-type': 'Bearer',
      'client': auth.client,
      'uid': '1',
      'X-Requested-With': 'XMLHttpRequest'
    },
    body: JSON.stringify(bodyRequest)
  })

I get the access-token in the response of the call for login

发现了错误,当您从rails中获取响应时,您得到了一个uid参数,它不是我想的整数,而是电子邮件...

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