Open antulik opened 2 years ago
A temporary patch
# config/initializers/devise_token_auth.rb
# https://github.com/lynndylanhurley/devise_token_auth/issues/1514
module DeviseTokenAuthCSRFPatch
def handle_unverified_request(*)
super.tap do
@resource = nil
end
end
end
DeviseTokenAuth::Concerns::SetUserByToken.include DeviseTokenAuthCSRFPatch
enable_standard_devise_support = true
protect_from_forgery with: :null_session
We have controller that is already using rails session for the authentication. We want to add token auth in addition. They will run in parallel to allow transition.
Adding
include DeviseTokenAuth::Concerns::SetUserByToken
to the controller works well, but CSRF is broken.After debugging it, this is why it happens:
current_user
, but since it's a first time we get user, we authenticate.set_user_by_token
is called, it sets@resource
instance variable.protect_from_forgery with: :null_session
handle_unverified_request
is calledcurrent_user
, which isnil
because it was cleared in the previous stepset_user_by_token
is called again to get userenable_standard_devise_support = true
we check devise. https://github.com/lynndylanhurley/devise_token_auth/blob/6d7780ee0b9750687e7e2871b9a1c6368f2085a9/app/controllers/devise_token_auth/concerns/set_user_by_token.rb#L58nil
(correct and expected)@resource
was previously set and wasn't cleared by invalid CSRF, we authenticate user and ignore invalid CSRF tokenExpected: Authentication should fail after session was reset
Actual: User is authenticated with invalid CSRF token.