devise-jwt icon indicating copy to clipboard operation
devise-jwt copied to clipboard

Users sometimes get logged into the wrong account

Open JohnGoodman opened this issue 11 months ago • 4 comments

In very rare instances, when a user has been logged in for a few days, when they come back to my app, they get logged into the wrong account. I'm not entirely sure what the cause is, but it likely has something to do with the stored JWT. Maybe the JWT isn't unique so when the person come backs and the session is re-authenticated via the stored JWT, a different user is found? Any help on this is appreciated.

I'm using Rails as a headless API that handles the user accounts. The web app is a React app. The web app stores the JWT in the browser's localstorage.

Rails: 8.0.0 devise-jwt: 0.12.1 devise: 4.9.4

JohnGoodman avatar Jan 21 '25 00:01 JohnGoodman

I'm pretty sure that should be something related to your setup. This is how the user is fetched from a JWT token by default. As you can see the primary key is used to match the token, so maybe you should investigate along that lines.

waiting-for-dev avatar Jan 21 '25 05:01 waiting-for-dev

@waiting-for-dev thanks for the reply. When I decode the JWT, it's giving me the user ID which I then use to look up the user account.

Today, I switched to using the 'HS512' hash algorithm in hopes that it solves the issue.

Here's the code if it helps:

user.rb

def generate_jwt
    JWT.encode({
      id: id,
      exp: 60.days.from_now.to_i
    }, Rails.application.secret_key_base, 'HS512')
  end

api_controller.rb

authenticate_or_request_with_http_token do |token|
  if request.headers['Authorization'].present?
    begin
      jwt_payload = JWT.decode(token, Rails.application.secret_key_base, true, {algorithm: 'HS512'}).first
      @current_user_id = jwt_payload['id']
    rescue JWT::ExpiredSignature, JWT::VerificationError, JWT::DecodeError
      head :unauthorized
    end
  else
    head :unauthorized
  end
end

JohnGoodman avatar Jan 22 '25 01:01 JohnGoodman

@JohnGoodman This is terrifying. Did you work out what was going on?

jonpauldavies avatar Mar 14 '25 08:03 jonpauldavies

@jonpauldavies no, I haven't been able to pinpoint the issue. However, after making the update to use the 'HS512' hash algorithm, I haven't heard any reports of the issue, so maybe that did fix it. Not really sure though.

JohnGoodman avatar Mar 17 '25 16:03 JohnGoodman