How to use jwt to complete the logout (logout) function



How to use jwt to complete the logout (logout) function

Magical JSON Web Tokens (JWT)

JSON Web Tokens (JWT) are a stateless way of handling user authentication. What’s the meaning?
JWT helps to establish authentication mechanism without storing authentication state in any storage, be it session memory or database, therefore, when checking user’s authentication state, there is no need to access session memory or perform database query. Instead, generate a token based on a user payload of your choice and use it in the client’s request to identify the user on the server

So basically, whenever a token is created, it can be used forever, or until it expires. The JWT generator can have an option to specify an expiration time when generating it.

But what should you do if you want to invalidate the generated token? What should you do when a user logs out or changes their password

log out

Usually when using JWT for authentication, the client stores the token somewhere and attaches it to each request that requires authentication, so the first thing to log out is to delete the token stored on the client (such as browsing Server local storage) In this case, the client does not have a token to request an interface that requires authentication, and will naturally get an unauthenticated response. But is that enough? This is a way to prevent gentlemen from villains. In fact, you can get the token through some means before logging out, and you can still use it after logging out! If you don’t believe me, you can try it yourself.
Let’s log out the token from the background, you may say bridge bean sack This is not so simple for jwt, you can’t delete the token like deleting cookies and sessions.

In fact, the purpose of JWT is different from that of session, and it is impossible to forcibly delete or invalidate the generated token.

Token expired

Yes, Token can be set to expire.
You can specify the expiration time when generating the token, you can add the exp field to the effective paylaod like this:

  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516234022,
  "exp": 1516239022

The exp field is a timestamp, and the iat field here represents the release time. This Token is set to expire 5 seconds after release⏰.
If you don’t want to have a token that is valid forever, you should set a reasonable expiration time for your JWT. The length of time depends on your application. We will use a token with a duration of one day here and generate them in the login operation. For NodeJS application, the code should look like this:

const jwt = require('jsonwebtoken');
const payload = {
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516234022
const token = jwt.sign(payload, 'your-secret', {expiresIn: '1d'})

When the token expires, the validator will return an error, and once the backend receives an authorization request, it will respond with an unauthorized response status. Typically, you will remove the token from the client and redirect the user to the login page. So in this example all users will be automatically logged out after 1 day of using your application.

Cool, but I still want to log out!

As mentioned, you can’t manually expire a token after it’s been created, and you can’t actually logout on the server side with a JWT like you can with a session or, unless, you can…
Using JWT should be stateless, which means you should store everything you need in the payload and skip performing DB queries on each request, but if you plan to have a strict logout function, you cannot wait for the Token to expire automatically , even if you have cleared the token from the client, then you may need to violate the stateless rule and perform some queries.

One possible implementation is to store a so-called “blacklist” of all Tokens that are valid and have not yet expired. You can choose a database that has a TTL function. TTL is used to record the amount of time remaining before the Token expires.Redisis a good option, this will allow fast access to the list in memory, then, in some middleware, running on each authorization request, you should check if the provided token is in the blacklist ️‍, if in throws an unauthenticated exception, if not let it pass, JWT validation will handle it and determine if it has expired or is still valid.

in conclusion

How to use jwt to complete the logout (logout) function
It seems that it is not so simple to create a clean logout process when using JSON Web Tokens, you should keep the Token active until it expires itself; or, if you want to limit the use of the Token when the user logs out, choose to store A Token blacklist. All in all, just follow these 4 key points:

  • Set a reasonable expiration time for the token
  • Delete stored token from client on logout
  • Has a database of no longer active tokens that still have some time to live
  • Query the authorization status according to the blacklist for each request

Recommended Today

What are the errors that try..catch cannot catch? What are the precautions?

Author: Ashish LahotiTranslator: Frontend XiaozhiSource: codingnconcept Search [Great Move to the World] on WeChat, and I will share with you the front-end industry trends, learning paths, etc. as soon as possible.This articleGitHub has been included, and there are complete test sites, materials and my series of articles for interviews with first-line manufacturers. In today’s content, […]