Nodejs authentication using JWT a.k.a JSON web token is very useful when you are developing cross-device authentication mechanism.
Here is how token based authentication works:
- User logins to the system and upon successful authentication, the user are assigned a token which is unique and bounded by time limit say 15 minutes
- On every subsequent API calls, the user provides the access token in order to consume the system resources.
- When time is expired, the user has to login again to get new token
The last step is frustrating, we can’t ask users to log in each and every single time once the token is expired.
There are two ways to solve this:
- Increase the time of the token
- Use refresh token to extend the token
JWT Keys:
- jwt
- jwt
/** jwt.sign is used to genrate token using below expression: **/
jwt.sign(payload, secretOrPrivateKey, [options, callback])
ex:
Synchronous Sign with default Algorithm (HMAC SHA256)
var jwt = ; // node module require to install
var token = jwt;
with Expiry time:
jwt
;
Sign asynchronously with Algorithm (HMAC SHA256)
jwt
;
/** jwt.verify is used to validate token using below expression: **/
// verify a token symmetric – synchronous
var decoded = jwt;
console // bar
// verify a token symmetric
jwt
;
Leave a Reply