JSON Web Tokens (JWT) are a popular way to add authentication and authorization to web and mobile applications. In NodeJS, you can use the jsonwebtoken package to create, verify, and decode JWT tokens. In this section, we'll explore how to work with JWTs in NodeJS and how to add extra information to a JWT token.
First, it is important to understand what a JWT is. A JWT is a compact and secure representation of a series of claims that can be exchanged between two parties. Claims are information that you want to convey securely between parties. A JWT token consists of three parts: a header, a payload, and a signature.
The header usually contains two parts: the token type, which is JWT, and the signature algorithm, such as HMAC SHA256 or RSA. The payload contains the claims you want to stream. Claims can be statements about an entity (usually the user) and additional data. The signature is used to verify that the sender of the JWT is who it claims to be and to ensure that the message has not been altered along the way.
To start working with JWTs in NodeJS, you will need to install the jsonwebtoken package. You can do this using npm, the NodeJS package manager, with the command: npm install jsonwebtoken.
Once installed, you can import the jsonwebtoken package into your code with the following command: const jwt = require('jsonwebtoken').
To create a JWT token, you can use the jwt.sign() method. This method accepts three arguments: the payload, a secret key, and an options object. The payload is the set of claims you want to include in the token. The secret key is used to sign the token and ensure its integrity. The options object can include various options such as the signature algorithm to use and the lifetime of the token.
For example, you can create a JWT token with the following claims: user ID and username, as follows:
let payload = { userId: '123', userName: 'John Doe' }; let secretKey = 'mySecretKey'; let options = { algorithm: 'HS256', expiresIn: '1h' }; let token = jwt.sign(payload, secretKey, options);
The resulting token will be a string that you can pass to the client. The client can then use this token to authenticate subsequent requests.
To add extra information to a JWT token, you can simply add more properties to the payload object. For example, if you want to add the user's email and user's role, you can do the following:
let payload = { userId: '123', userName: 'John Doe', userEmail: 'john.doe@example.com', userRole: 'admin' }; let token = jwt.sign(payload, secretKey, options);
This extra information will be included in the JWT token and can be used to make authorization decisions on the server. For example, you can check the user's role to determine if they have permission to access a specific resource.
To verify a JWT token and extract the claims, you can use the jwt.verify() method. This method takes three arguments: the token, the secret key, and an options object. The method returns the payload if the token is valid and throws an error if the token is invalid or expired.
For example, you can verify a token and extract the claims as follows:
let token = '...'; // the JWT token received from the client try { let payload = jwt.verify(token, secretKey); console.log(payload); } catch (err) { console.log('Invalid or expired token'); }
The resulting payload object will contain all of the claims you included when creating the token, including any extra information you added.
In summary, JWTs are a powerful and flexible way to add authentication and authorization to your NodeJS applications. You can include any information you like on the token, as long as you are aware that the information on the token can be read by anyone who has the token. Therefore, you should avoid including sensitive information in the token unless the token is encrypted.