You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
14 Hrs
49 Min
32 Seg
Curso de Backend con ExpressJS

Curso de Backend con ExpressJS

Oscar Barajas Tavares

Oscar Barajas Tavares

Autenticaci贸n utilizando JSON Web Tokens (JWT)

18/30
Resources

JSON Web Token (JWT) authentication is a fundamental technique for securing modern web applications. This method allows to verify the identity of users and control access to specific resources in an efficient and secure way. In the following, we will explore how to implement this authentication system in a Node.js application, from installing the necessary dependencies to creating protected routes.

How to implement authentication with JSON Web Token?

To implement an authentication system based on JWT, we need to install some dependencies that will make our work easier. These tools will allow us to create users, authenticate them and generate tokens that will control access to protected routes.

The first thing to do is to install the necessary libraries:

npm install jsonwebtokennpm install bcryptjs

The first library will allow us to work with JWT tokens, while the second will help us to encrypt user passwords to store them securely in our database.

Creating the authentication middleware

The next step is to create a middleware that will verify the validity of the tokens in each request to protected paths. To do this, we will create a file called auth.js in the middlewares folder:

const JWT = require('jsonwebtoken');
function authenticateToken(req, res, next) { const token = req.headers.authorization?.split(' ')[1];    
 if (!token) { return res.status(401).json({ error: "Access denied. No token provided." }); }    
 JWT.verify(token, process.env.JWT_SECRET, (error, user) => { if (error) return res.status(403).json({ error: "Invalid token" });        
 req.user = user; next(); }); });}
module.exports = authenticateToken;

This middleware performs the following actions:

  1. Extracts the token from the authorization header.
  2. Checks if there is a token in the request
  3. Validates the token using the secret key stored in the environment variables
  4. If the token is valid, stores the user information in the request object and allows the request to proceed

It is important to set the JWT_SECRET environment variable in our configuration file:

JWT_SECRET=Platzi

This secret key must be secure and unique for each application, as it is essential for the security of the authentication system.

Implementing protected routes

Once we have our authentication middleware, we can implement it on the routes we want to protect. To do this, we first import the middleware into our main file:

const authenticateToken = require('./middlewares/auth');

Then, we create a protected route that will use this middleware:

app.get('/protected-route', authenticateToken, (req, res) => { res.send("This is a protected route");});

With this configuration, any request to the /protected-route will first go through the authenticateToken middleware, which will check if the provided token is valid before allowing access.

How to test authentication with Postman?

To verify that our authentication system is working properly, we can use Postman to make requests to our API:

  1. Create a new GET request to the protected path(http://localhost:3000/protected-route).
  2. In the "Headers" tab, add a header called "Authorization" with the value "Bearer [token]".
  3. Send the request

If we do not provide a token or if the token is invalid, we will receive an access denied error. On the other hand, if the token is valid, we will be able to access the protected path.

Expected behavior

  • No token: 401 response - "Access denied. No token provided."
  • Invalid token: 403 Response - "Invalid token".
  • Valid token: Access to the protected path

It is important to note that in order to obtain a valid token, we will need to implement additional routes for user registration and authentication, where we will generate the JWT tokens after verifying the credentials.

The implementation of JWT authentication is a fundamental step in securing our web applications. This system allows us to verify the identity of users in an efficient and secure way, controlling access to specific resources. Have you ever implemented this type of authentication in your projects? Share your experience in the comments.

Contributions 0

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?