Users sometimes get logged into the wrong account
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
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 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 This is terrifying. Did you work out what was going on?
@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.