Summary
Highlights
The video introduces JWT authentication using Node.js and Express, outlining two main parts: simple authentication and refresh tokens. It then walks through setting up the project by initializing npm, installing Express, JSON Web Token, and dotenv, and configuring nodemon for automatic server restarts. A basic Express server is created with a GET route to retrieve a list of predefined posts.
This section focuses on adding JWT authentication to protect the posts. A POST route for login is created, where a username is received in the request body. The video explains the process of signing a JWT with the user's information and a secret key (stored in a .env file) to create an access token. It uses the `crypto` library to generate a strong secret key. An access token is then returned to the user.
An `authenticateToken` middleware function is developed to verify the JWT. This middleware extracts the bearer token from the authorization header, checks for its existence, and then uses `JWT.verify` with the secret key to validate the token. If the token is valid, the user's information is attached to the request object; otherwise, appropriate error status codes (401 for missing token, 403 for invalid token) are returned.
The tutorial highlights the advantage of JWTs in a multi-server environment. It sets up a second Express server on a different port, demonstrating that a JWT generated by one server can be authenticated by another, as long as they share the same secret key. This illustrates the stateless nature of JWTs and their suitability for distributed systems.
The video introduces the concept of refresh tokens to improve security. The authentication logic is moved to a dedicated 'auth server' (port 4000), while the main server (port 3000) handles application-specific data. An `generateAccessToken` function is created, setting a short expiration time (15 seconds for demonstration) for access tokens. A separate refresh token, without an expiration date, is also created and returned during login, along with the access token.
A new POST endpoint `/token` is added to the auth server to handle refresh token requests. This endpoint receives a refresh token, checks if it's valid (stored in a local array for demonstration, but ideally in a database), and then uses `JWT.verify` with the refresh token secret. If valid, a new, short-lived access token is generated and returned. This allows users to obtain new access tokens without re-authenticating with their credentials.
To enable logout and revoke user privileges, a DELETE endpoint `/logout` is implemented on the auth server. This endpoint receives a refresh token and removes it from the list of valid refresh tokens. This prevents the user from generating new access tokens with the invalidated refresh token, effectively logging them out. The video concludes by demonstrating the entire flow of getting an access token, refreshing it, and logging out.