“Learn how to implement JWT Authentication and Authorization in NestJS. This guide explains the basics of JWT, its role in securing web applications, and how to set it up in NestJS with practical examples. Ideal for developers looking to secure their APIs using JWT.”
Imagine you have a magical key that lets you enter your favorite amusement park. This key has your name and details written on it, so everyone knows it’s yours. JWT, or JSON Web Token, is like that magical key, but for computers. It’s a small, secure package of information that proves who you are when you visit different areas of a web application.
Table of Contents
Why Do We Need JWT?
Let’s say you visit the amusement park, and every time you want to go on a ride, someone asks you, “Who are you?” Wouldn’t it be annoying to show your ID over and over? Instead, JWT acts like an all-access pass! Once you have it, you don’t need to prove yourself again and again.
In web applications:
- Authentication checks who you are.
- Authorization decides what you can do.
JWT helps with both!
Setting Up JWT in NestJS
NestJS is like a friendly chef who helps you cook delicious meals (web applications). Here’s how you add JWT to your project:
- Install Dependencies Open your terminal and type:
npm install @nestjs/jwt passport-jwt @nestjs/passport passport
- Set Up the Auth Module Create a new module for authentication:
nest generate module auth nest generate service auth
- Create the JWT Strategy Add a file called
jwt.strategy.ts
:import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'supersecretkey', // Use environment variables
});
}
async validate(payload: any) {
return {
userId: payload.sub,
username: payload.username
}; } }
- Generate Tokens In your
auth.service.ts
:import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
constructor(private jwtService: JwtService) {}
async login(user: any) {
const payload = {
username: user.username,
sub: user.userId };
return { access_token: this.jwtService.sign(payload), }; } }
- Protect Routes
Use a guard to lock down routes:import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
Add it to your controller:@UseGuards(JwtAuthGuard)
@Get('protected')
getProtectedResource() {
return 'This is a protected route!';
}
Interview Questions and Answers
Q1. What is JWT?
A: JWT, or JSON Web Token, is a compact, self-contained way to represent information between two parties. It’s commonly used for authentication and securely transmitting information.
Q2. How does JWT work in NestJS?
A: JWT works in NestJS by generating a token during authentication. This token is then validated in protected routes using a strategy like passport-jwt
.
Q3. What’s the difference between Authentication and Authorization?
A:
- Authentication: Who are you?
- Authorization: What are you allowed to do?
Q4. How do you ensure the security of JWT?
A:
- Use strong secret keys.
- Store tokens securely (e.g., HTTP-only cookies).
- Set short expiration times.
- Use HTTPS to prevent interception.
Q5. What are the common components for setting up JWT in NestJS?
A:
@nestjs/jwt
for managing tokens.passport-jwt
for validating tokens.- Auth guards and strategies for protecting routes.
Companies Asking About JWT Authentication
Here are some companies known to focus on JWT-related concepts during interviews:
- Amazon Web Services (AWS)
- Infosys
- Globant
- TCS (Tata Consultancy Services)
- Accenture
Good luck writing your blog and acing those interviews, Aishw! If you need more help, let me know. 🚀