What is JWT authentication in Node.js?
What is JWT authentication in Node.js?
JWT (JSON Web Token) authentication in Node.js is a stateless token-based authentication system that ensures the authentication of user identity and access control to authenticated resources. It also helps remove the requirement of the server to retain the session data, enhancing scalability and efficiency, particularly in ad hoc systems or microservices.
How it Works
The process involves a specific flow between the client and the Node.js server:
- User Login: The customer forwards their user name/email and password to the Node.js server.
- Token Generation: When the credentials are authentic, the server produces a JWT with the help of a library such as the jsonwebtoken package and a secret key that only the server knows. The token comprises user information (claims) and a validity period.
- Token Transmission: The JWT is returned to the client by the server and stored (e.g. in memory or an HTTP-only cookie).
- Accessing Protected Routes: In all the further requests to secure paths, the customer uses the JWT, which is usually contained in the Authorization header in the form of Bearer
. - Token Verification:The Node.js server will then retrieve the token, and confirm its signature using the identical secret key and determine its validity (e.g. whether it has expired).
- Access Granted/Denied: In case the token is authentic, the server gives access to the requested resource. Otherwise it either gives out a 401 (Unauthorized) or 403 (Forbidden) response.
JWT Structure
A JWT is a short string that is made up of three parts with dots between :
- Header: Has metadata on the token, including the type of token (JWT) and the cryptographic algorithm to sign the token with (e.g., HS256 or RS256).
- Payload: Includes claims, statements regarding the user (such as user ID, role and email), and other information such as expiration time (exp). This is an unencrypted (not encrypted) part and thus sensitive data must not be saved as one.
- Signature: A hash of the encrypted header, the encrypted payload and the secret key of the server. This signature plays a vital role in ensuring that the server can be able to check that the token has not been altered and is genuine. On jwt.io, you can learn about and decode the structure of a sample JWT.
Advantages in Node.js
- Stateless: The server does not need to hold a state of the session; hence it is easy to up-scale the application to a number of servers.
- Scalability: It is ideal in a microservice architecture since any service having the shared secret key can authenticate the token.
- Efficiency: Eliminates the necessity to query the database every time an identity needs to be verified by the user.
- Cross-Platform: JWTs are relatively small, so they can be applicable across various platforms, such as web browsers, mobile applications, and APIs.
Abarna Vijayarathinam Asked question
