Implementing authentication NestJS and set jwt token to header with custom decorator
Assistant
User
nestjs add JWT token to requests.header.autorization.
Assistant
To implement authentication in NestJS and set a JWT token to the header with a custom decorator, you'll need to follow these steps. We'll cover setting up JWT authentication, creating a custom decorator to extract the JWT token, and implementing this decorator to secure your endpoints.
Step 1: Setting up JWT Module
First, ensure you have the necessary packages installed:
Create an auth module if you don't have one already:
bash
nest g module auth
Within the auth module, initialize the PassportModule and JwtModule. For the JwtModule, you'll need to provide a secret and an expiry time for the tokens.
typescript
// auth.module.ts
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: 'yourSecret', // In a real app, make sure to use a strong secret and store it safely
signOptions: { expiresIn: '60s' },
}),
// other modules like UsersModule
],
// controllers: [AuthController],
// providers: [AuthService, JwtStrategy],
})
export class AuthModule {}
Step 2: Create JWT Strategy
Create a JWT strategy for Passport to handle authentication using JWT tokens.
Now, you can use your custom GetJwtToken decorator in your controllers to extract the JWT token from requests.
typescript
// app.controller.ts
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { GetJwtToken } from './path/to/decorators/get-jwt.decorator';
@Controller()
export class AppController {
@Get('protected')
@UseGuards(AuthGuard('jwt'))
getProtectedResource(@GetJwtToken() token: string) {
// `token` now contains your JWT token
console.log(token);
return { message: 'This is a protected route' };
}
}
Conclusion
With these steps, you have set up JWT authentication in your NestJS application and created a custom decorator to extract JWT tokens from requests. This allows you to secure your routes and easily access authentication-related data when needed. Always remember to keep your JWT secret secure and handle tokens and user data carefully for the safety of your application and its users.
To add a JWT token to the Authorization header for outgoing requests in a NestJS application, you can create an interceptor or use a service depending on where and how you'd like to implement this functionality. Below are two common approaches:
Approach 1: Using an Interceptor
An interceptor is perfect for adding tokens to outgoing HTTP requests globally or contextually within your application.
Install HTTP Module: First, ensure you have the @nestjs/axios package installed for making HTTP requests.
bash
npm install @nestjs/axios
Create an HTTP Config Service: This service can retrieve/store the JWT token. For a simple case, you can pass the token directly, but typically, you'd retrieve it from a request or a storage mechanism.
Creating the Interceptor:
typescript
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { Observable } from 'rxjs';
import { AxiosRequestConfig } from 'axios';
import { mergeMap } from 'rxjs/operators';
@Injectable()
export class JwtInterceptor implements NestInterceptor {
constructor(private readonly httpService: HttpService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
// Assume getToken() retrieves your JWT token
const token = this.getToken();
const axiosRequest: AxiosRequestConfig = context.getArgByIndex(0);
if (token) {
axiosRequest.headers.Authorization = `Bearer ${token}`;
}
return next.handle().pipe(
mergeMap((data: any) => {
// You can modify the response if necessary
return data;
}),
);
}
private getToken(): string {
// Retrieve your token from wherever it is stored
return 'your-jwt-token';
}
}
Apply the Interceptor Globally or Locally: To apply it globally, modify your app.module.ts or a specific module to use your interceptor.
typescript
import { APP_INTERCEPTOR } from '@nestjs/core';
import { JwtInterceptor } from './jwt.interceptor';
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: JwtInterceptor,
},
// other providers
],
})
export class AppModule {}
Alternatively, you can apply it to a specific controller or method by using the @UseInterceptors() decorator.
Approach 2: Manual Inclusion in a Service
If you're handling a specific external API call and just need to include the JWT token in that request, you can do so directly within the service making the request.
Injecting HTTPService: First, ensure you inject the HttpService into your service constructor.
Including the JWT Token:
typescript
@Injectable()
export class SomeService {
constructor(private readonly httpService: HttpService) {}
async makeAuthenticatedRequest() {
const token = 'your-jwt-token'; // Get this dynamically as needed
const headersRequest = {
Authorization: `Bearer ${token}`,
};
return this.httpService.get('https://external-api.com/data', { headers: headersRequest }).toPromise();
}
}
In this approach, you directly manipulate the headers of the request within the service method making the external call.
Conclusion
Both approaches have their uses: interceptors are powerful for applying logic globally or contextually across outgoing requests, while manual inclusion within services is straightforward for targeted use cases. Choose the approach that best fits your application's structure and needs.