Refresh token (access token)

  • Do not use JWT (Just DON’T)
  • Always have a sessions table
    • Which belongs to the USER
      • i.e., sessions table has a user_id column
    • Have access_token and refresh_token
      • ideally as varchar(256), not text
      • do not allow them to grow
      • security shall be mostly based on rotation, not purely on length
    • Must have access_token_expires_at and refresh_token_expires at columns (both datetime, and keep them as UTC)
      • make sure to have these columns calculated during the creation of the session. Do not think of doing “time-math” for calculating expiry.
        • Because, you may login with one server, but the next server you have the auth checked might have a different time stamp/zone
    • access/refresh tokens shall be unique
  • From the above, it becomes possible to have multiple active sessions for one user.
    • If that is not desired, restrict that at code level, not at DB level
  • Generate random strings for access token and refresh token
    • keep them URLsafe (you’ll thank me when you have a mobile app)
    • Keep them about 256 char long
      • no longer
      • no shorter
  • Make access_expiry in a few minutes, and refresh_expiry in a few days
  • Standard auth is having authorisation header
    • Authorisation: Bearer <access-token>
  • Refresh token will require
    • Authorisation: Bearer <refresh-token>
  • Deal with Auth always in a middleware and keep the logged in user, or the session found by looking up the access_token (or refresh_token) in the sessions table
  • On refresh, delete the current session object, and create a new one with new
    • access_token, and new expiry in a few minutes
    • refresh_token, with new expiry in a few days
  • Disallow refresh if the refresh token is already expired
  • So, if a user logs in and is inactive for a few days, the refresh token expires, and they will have to login fresh again
  • But as long as the user does a “refresh” before the refresh-token is expired, they will have sessions alive always.