Guide to Using NestJS JWT
Introduction
JSON Web Token (JWT) is an open standard (RFC 7519) used for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.
- Advantages: No need to store sessions on the server (Stateless), easy system scalability, good support for multi-platform applications and microservices.
- Limitations: Difficult to revoke tokens before expiration, token size larger than session ID, and if the Secret Key is exposed, the entire system will be compromised.
Detail
After creating the NestJS project, create the auth.dto.ts file to define the payload information when logging in with the following content:
Create the environment.service.ts file:
This code snippet is used to read and centrally manage JWT-related environment variables (env), such as secret keys and token expiration times.
Create the jwt.strategy.ts file:
This class defines the method for validating the Access Token from the request Header, checking the validity of the token sent from the user side against information from the server, and decoding user information from that token.
Create the jwt.guard.ts file to define a guard based on the 'jwt' strategy created above:
Create the jwt-refresh.strategy.ts file:
This strategy is also similar to JwtStrategy, but pay attention to the secretOrKey part, which uses envService.jwtRefreshSecret because this strategy is used for refreshing the token.
Create the jwt-refresh.guard.ts file to use the JwtRefreshStrategy:
Create the auth.service.ts file:
- This is where the main business logic is processed, including checking the account, creating a new pair of Access/Refresh Tokens, and retrieving user information.
- Here, I have hard-coded the user information for demo purposes; in reality, this information would be retrieved from a database.
Create the auth.controller.ts file:
- This class defines the HTTP endpoints (login, refresh, profile) and applies Guards to protect routes that require login.
- Note that /refresh uses JwtRefreshAuthGuard, which requires sending up the refresh token, while /profile uses JwtAuthGuard, which requires sending up the access token.
Update the app.module.ts file:
This is the application's general configuration file, where modules are connected, JwtModule is registered globally, and necessary controllers and providers are declared.
Finally, edit the .env file with values according to your needs:
Testing the API with Postman yields the following results:
Happy coding!
Comments
Post a Comment