Working with JSON Web Tokens (JWT) in NodeJS

Capítulo 109

Estimated reading time: 4 minutes

+ Exercise
Audio Icon

Listen in audio

0:00 / 0:00

JSON Web Tokens (JWT) is an open standard (RFC 7519) that defines a compact, self-contained way to pass information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

When building APIs in NodeJS, JWT plays a crucial role in authentication and authorization. It allows users to authenticate, and once authenticated, they receive a JWT. This token is then used to authorize the user to access routes, services and resources that are allowed with this token. This makes JWT an indispensable tool for building secure APIs.

Implementing JWT in NodeJS is pretty straightforward, thanks to packages like jsonwebtoken. To get started, you need to install the jsonwebtoken package using npm.


npm install jsonwebtoken

Once installed, you can import the package into your file and start using it to create and verify tokens.


const jwt = require('jsonwebtoken');

To create a token, you use the sign() method. This method accepts three arguments: the payload, the secret, and the options. The payload is the object that contains the claims. Claims are statements about an entity (usually the user) and additional information. The secret is the secret key used to sign the token. Options are used to set other properties of the token, such as the signature algorithm and token expiration.

Continue in our app.
  • Listen to the audio with the screen off.
  • Earn a certificate upon completion.
  • Over 5000 courses for you to explore!
Or continue reading below...
Download App

Download the app


let payload = {username: 'user'};
let secret = 'somesecretkey';
let token = jwt.sign(payload, secret, {expiresIn: '1h'});

To verify a token, you use the verify() method. This method accepts three arguments: the token, the secret, and a callback function. The callback function is called with the verification result.


jwt.verify(token, secret, function(err, decoded) {
  if (err) {
    console.log('Token verification failed');
  } else {
    console.log('Token verified successfully');
  }
});

An important thing to note is that you should always protect the secret used to sign the token. If someone has access to your secret, they can sign tokens themselves, which can lead to serious security issues.

In addition, you should always verify the token before allowing the user to access protected routes, services, or resources. This can be done using middleware that verifies the token on every request.


function authenticateToken(req, res, next) {
  const token = req.headers['authorization'];
  if (token == null) return res.sendStatus(401);

  jwt.verify(token, secret, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

In summary, JWT is a powerful tool for authentication and authorization in NodeJS APIs. It allows you to create tokens that can be used to authenticate users and authorize them to access routes, services and resources. Implementing JWT in NodeJS is simple thanks to packages like jsonwebtoken.

Now answer the exercise about the content:

What is the main role of JSON Web Tokens (JWT) in creating APIs in NodeJS?

You are right! Congratulations, now go to the next page

You missed! Try again.

The primary use of JSON Web Tokens (JWT) in NodeJS APIs is for user authentication and authorization. JWT allows users to authenticate and get a token, which is then used to authorize them to access specific routes, services, and resources.

Next chapter

Working with JSON Web Tokens (JWT) in NodeJS: What are JSON Web Tokens (JWT)

Arrow Right Icon
Free Ebook cover How to create APIs in NodeJS from basic to advanced
73%

How to create APIs in NodeJS from basic to advanced

5

(1)

149 pages

Download the app to earn free Certification and listen to the courses in the background, even with the screen off.