lynndylanhurley / devise_token_auth

Token based authentication for Rails JSON APIs. Designed to work with jToker and ng-token-auth.
Do What The F*ck You Want To Public License
3.54k stars 1.13k forks source link

CSRF protect_from_forgery with: :null_session is skipped #1514

Open antulik opened 2 years ago

antulik commented 2 years ago

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:

Expected: Authentication should fail after session was reset

Actual: User is authenticated with invalid CSRF token.

antulik commented 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