Access Tokens via JWTs

grahamcox82

Graham Cox

Posted on January 9, 2017

Access Tokens via JWTs

It's becoming quite common practice these days to use a Json Web Token (JWT) as the Access Token format for accessing web APIs. The reason being that they are self contained, and cryptographically secure from tampering. And that's fantastic.

Firstly, what is a JWT? Simply put, it's a bag of data - which are called claims - and a cryptographic signature to verify who generated it. If the signature is invalid, the JWT must be ignored, and because nobody else has the signing keys you know they aren't forged.

There are a standard set of claims defined, but you can add any you want. The standard ones are:

  • Issuer - who created the JWT
  • Subject - who the JWT represents
  • Audience - who the JWT is for
  • Expiration - when the JWT ceases to be valid
  • Not before - when the JWT starts to be valid
  • Issued at - when the JWT was created
  • Id - a unique identifier for the JWT

The difference between Subject and Audience isn't immediately apparent, but is important. Subject is the user this JWT is an authentication token on behalf of, Audience is the client that is making use of the token.

The fact that JWTs have expiry built in if very useful too. It means I can issue one, and the login session is dictated by the expiry time. If I need to extend it, I can just issue a new one (OAuth2 defines this as Refresh Token).

So does this mean I can avoid all database lookups during the authorization flow? I know who the user is, and I know that the session is valid. Is that enough?

No it's not. There are three extra things you need, and one of those can not be stored in the JWT.

Firstly - is the user allowed to perform this action? This can be stored in the JWT as a collection of the users roles. That was simple.

Secondly - is the user account banned? This might have changed since they logged in, and it might be important to honour it immediately, so this needs looking up in the database every time. Now, if you have short lived tokens and are ok with banning a user taking this time you can avoid this too.

Thirdly - is the Token still valid? This means two things - has the token been revoked, and has the audience been revoked? Again, with short lived tokens and an acceptance of the fact that revocation taking time this can be avoided too.

So, can we avoid database lookups during authorisation? Maybe, but that's depends on how you balance security against performance and ease of use.

The important thing is to not just blindly assume that JWTs mean no database lookups. It can, but it probably shouldn't.

💖 💪 🙅 🚩
grahamcox82
Graham Cox

Posted on January 9, 2017

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Access Tokens via JWTs
100daysofcode Access Tokens via JWTs

January 9, 2017