5

Is there a way to refresh a JWT token provided by devise-jwt in Rails? Or is the best practice to force the user to re-authenticate?

Such
  • 910
  • 1
  • 9
  • 20
  • This was actually answered in this issue: https://github.com/waiting-for-dev/devise-jwt/issues/7 – Such Dec 14 '18 at 07:57
  • 1
    Not really answered in that thread @such ... the answer being "do it on every request" (without an example) or "use a different gem". – David Parker Oct 25 '20 at 17:10

2 Answers2

0

What I ended up doing is this:

In my allowlist:

def self.jwt_revoked?(payload, user)
  # Hook in here to refresh token
  token = user.allowlisted_jwts.where(payload.slice('jti', 'aud')).first
  if token.present? && (SOME LOGIC ABOUT YOUR EXPIRATION HERE)
    token.update_column(:exp, Time.now + SOME TIME)
  end
  token.blank?
end

There I would check the expiration. For example, if your token lasts 60 seconds and you want to refresh if at least 30 seconds old. You could write:

if token.present? && token.exp < (Time.now+30.seconds)
  token.update_column(:exp, Time.now+60.seconds)
end
David Parker
  • 128
  • 2
  • 13
  • According to devise-jwt README, the `jwt_revoked?` hook now has to be added to the model depending of the Allowlist strategy. Here, user. – ldlgds May 07 '23 at 13:49
0

It now should be in case of an Allowlist like this:

models/user.rb:

def self.jwt_revoked?(payload, user)
  token = user.allowlisted_jwts.where(payload.slice('jti', 'aud')).order(created_at: :desc).first
  return true if token.blank?

  token.update(exp: Time.current + SOME_DELAY)
  false
end
ldlgds
  • 123
  • 1
  • 7