Introducci贸n a Node.js y Express
Node.js y Express
Entorno de trabajo
Variables de entorno
Rutas din谩micas
Body parser
Postman
CRUD
驴Que es una API Restful?
Solicitudes GET
Solicitudes POST
CRUD
Soluci贸n del reto de validaci贸n
Solicitudes DELETE
MIddlewares
Middlewares - logger
Middlewares - ErrorHandler
DB
Instalar Postgresql
Instalar Prisma y PostgreSQL Client
Prisma Models
JWT
Autenticaci贸n utilizando JSON Web Tokens (JWT)
Auth - Register
Auth - Login
Expres.js
Arquitectura
Arquitectura parte 2
Creaci贸n y Migraci贸n de Modelos con Prisma para Citas M茅dicas
Admin controllers / services
Admin controllers / services parte 2
Reservations
Reservations parte 2
Appointments
Deploy
PostgreSQL
Deploy
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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.
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:
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.
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.
To verify that our authentication system is working properly, we can use Postman to make requests to our API:
(http://localhost:3000/protected-route).
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.
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
Want to see more contributions, questions and answers from the community?