Authentication

How to manage login activity using JWT in NodeJs

Manage Login Activity of User

Divyansh Agarwal
The Startup
Published in
7 min readJun 20, 2020

About JWT

JWT (JSON Web Tokens) is a stateless way of handling authentication in our app. For each login request, the server generates a token and sends it to the front-end where it is stored and used to authenticate every other request.

But since the JWT is stateless it (should not be) is not stored in any database or storage. So if a user wants to logout from a particular device or logout from all the devices, he cannot logout using the traditional way of authentication using JWT. What if I tell you there is a way to solve this problem without changing the stateless nature of JWT, and without even using any secondary storage like Redis.

Problem with using Redis for storing tokens

Redis is an open-source, in-memory data structure store, which is generally used as a database, cache, and message broker. So to implement logout from all device functionality, the token must be blacklisted and since the JWT is stateless it is not recommended to store the token in the database. So here comes the Redis which acts as an intermediate data store in which the user’s token is stored and when the user wants to logout from all the devices, the backend just gets all the user’s tokens and blacklists them. So the biggest issue in using Redis is that in this method the token is stored in a common data store that effects the stateless nature of the token. Also, it is difficult to keep track of which token is used to login with which device for a user.

Problem with using Session authentication

Although implementing logout from all devices functionality using a session is an easy task and there are many problems related to Session Authentication. First, the session id must be stored in a cookie in the browser which could bring unreliability to the authentication mechanism. Second, unlike token-based authentication, the session-based authentication is not stateless. Sessions vs Token Authentication can be a hot topic to discuss but we are not here to discuss that.

Solution

--

--

Divyansh Agarwal
The Startup

I am an Innovator with lots of ideas in my mind to improve the world for better! Know more about me at https://divyanshagarwal.info .

Recommended from Medium

Lists

See more recommendations