4

I'm using django-rest-framework-jwt in one of my APIs. As you might know, the concept is simple: you send username and password and you get a token back. The token is not stored anywhere on the server.

By sending the token in the header of subsequent requests, the user associated with the token is extracted from database. I'm curious as to how this is implemented. How the server can extract the user and also the expiration time of the token by just having the token?

I know the concept of public/private keys but if this is implemented with the same idea, what would be the private and public key here?

5

A JWT token consists of a base64 encoded string containing header, claims and signature.

The claims section contains a JSON encoded expiration field, exp:

Expiration time. It contains the UTC Unix time after which you should no longer accept this token. It should be after the issued-at time.

The username can also be stored in the claims object.

There are two options regarding "signing" of the JWT:

JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.

With the secret, there is a private key, however this is used to authenticate the message using HMAC SHA256. There is no encryption, just authentication so a client could work out what was stored in the token, but not change it. HMAC is a way of calculating hashes without them being vulnerable to length extension attack. There is no public key in this method.

With RSA, the private key is used to sign the key, which can be verified using the public key when received by a client. Therefore only the component generating keys needs to know the private key.

See Understanding JWT for more information.

  • Three years later I noticed I did not upvote this answer despite having accepted it. – norbertpy Mar 25 '18 at 18:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.