JSON Web Token (JWT)
JSON Web Token is a library for generating and verifying JSON Web Tokens (JWTs).
The JWT module is available via the following require()
statement in PubNub Functions:
1const {sign, decode, verify} = require('jwt');
Exposed methods
Use these methods in your Function code:
decode
— Extract the payload and, optionally, the header from a token without verifying its signature.verify
— Verify a token with a secret or public key and validate expected claims.sign
— Create and sign a token from a payload and a secret or private key.
Examples
- Decode
- Verify
- Sign
1const jwt = require('jwt');
2
3// Example token (this should be a valid JWT)
4const token = 'your.jwt.token.here';
5
6const decoded = jwt.decode(token, { complete: true });
7console.log('Decoded Token:', decoded);
The decode
method returns the token’s payload, and if { complete: true }
is set, it returns an object containing both the payload and the header.
With { complete: true }
:
Decoded Token: {
header: { alg: 'HS256', typ: 'JWT' },
payload: { userId: '123456', username: 'johndoe', iat: 1616239022, exp: 1616242622 },
signature: 'h04J3jUOeGXRHgZzg28pzF5omFxCeK2FlhEXbPZnQ'
}
Without { complete: true }
:
Decoded Token: { userId: '123456', username: 'johndoe', iat: 1616239022, exp: 1616242622 }
1const jwt = require('jwt');
2const secretKey = 'your-256-bit-secret';
3
4// Example token (ensure you replace this with a valid token signed with the `secretKey`)
5const token = 'your.jwt.token.here';
6
7try {
8const decoded = jwt.verify(token, secretKey);
9console.log('Decoded Payload:', decoded);
10} catch (err) {
11console.error('Token verification failed:', err.message);
12}
If the token is successfully verified, the verify
method returns the decoded payload (or the full token data if complete: true
is specified). If verification fails (due to tampering, expiration, or using the wrong key), it throws an error.
If successful:
Decoded Payload: { userId: '123456', username: 'johndoe', iat: 1616239022, exp: 1616242622 }
If verification fails:
Token verification failed: jwt expired
The error message will vary depending on the reason for failure, such as expiration or invalid signature.
1const jwt = require('jwt');
2
3const payload = {
4userId: '123456',
5username: 'johndoe'
6};
7
8const secretKey = 'your-256-bit-secret';
9
10const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
11console.log('Generated Token:', token);
The sign
method returns a JWT as a string. This token can be used in your application for authentication and authorization purposes.
Generated Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NTYiLCJ1c2VybmFtZSI6ImpvaG5kb2UiLCJpYXQiOjE2MTYyMzkwMjIsImV4cCI6MTYxNjI0MjYyMn0.g8h04J3jUOeGXRHgZzg28pzF5omFxCeK2FlhEXbPZnQ
The actual token value will differ each time you generate it due to the timestamp and signature.
Functions support
Functions provides a rich set of tools. For help with situations not covered here, contact PubNub Support.