flask-jwt How handle a token? flask-jwt How handle a token? flask flask

flask-jwt How handle a token?


JWTs consist of three parts separated by dots (.), which are:

  • Header
  • Payload
  • Signature

Therefore, a JWT typically looks like the following.

xxxxx.yyyyy.zzzzz

Let's see a brief summary according to RFC and this

Header

The header typically consists of two parts: the type of the token, which is JWT, and the hashing algorithm such as HMAC SHA256 or RSA.

{  "alg": "HS256",  "typ": "JWT"}

Payload

The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional metadata. This is the interesting part because inside the token we can check which your belongs.{ "userid": "1234567890", "expiration_date": "2016-05-129"}

When we generate a new token we can specify the data will payload contains so we can add userid to identify a user and expiration_date to check if is time to ask for a new one.

Signature

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message was’t changed in the way.

Server side

We should keep our secret key in server side, hence, we can decrypt a valid payload and check which user belongs. In this way we are free to avoid store tokens, because every token store itself enough data to validate our users.

How renew the token?: from client side

The process to generate a renewed token is the same, so the client side should ask for a renew service(HTTP request like www.myhost.com/renew) and send the old token to generate the new one. Remember you can check what user belongs that token hence the renew token should contains the same payload but with different expiration date.

Single sign-on

We can use JWT with more strategies like single sign-on to ensure only one user with same credentials is logged at same time.