Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS passing Authorization header to HttpService

I have a NestJS application which acts as a proxy between a front-end and multiple other back-ends.

I basically want to be able to pass a specific header (Authorization) from incoming @Req (requests) in the controller to the HttpService that then talks to the other back-ends.

user controller (has access to request) -> user service (injects httpService that somehow already picks the Authorization header) -> External backends.

Right now I need to extract the token from @Headers and then pass token to service which has to paste it to all HttpService calls.

Thanks in advance!

like image 800
Nine Magics Avatar asked Mar 29 '26 20:03

Nine Magics


2 Answers

Besides the middleware answer, I have another version using interceptor:

@Injectable()
export class HttpServiceInterceptor implements NestInterceptor {
  constructor(private httpService: HttpService) {}
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
  
    // ** if you use normal HTTP module **
    const ctx = context.switchToHttp();
    const token = ctx.getRequest().headers['authorization'];

    // ** if you use GraphQL module **
    const ctx = GqlExecutionContext.create(context);
    const token = ctx.getContext().token;

    if (ctx.token) {
      this.httpService.axiosRef.defaults.headers.common['authorization'] =
        token;
    }
    return next.handle().pipe();
  }
}

If you use GraphQLModule, do not forget to pass token to context:

GraphQLModule.forRoot({
  debug: true,
  playground: true,
  autoSchemaFile: 'schema.gql',
  context: ({ req }) => {
    return { token: req.headers.authorization };
  },
}),

Once preparation work is ready, let's use interceptors

The interceptor can be injected into a certain controller:

@UseInterceptors(HttpServiceInterceptor)
export class CatsController {}

or register a global interceptor like following:

@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: HttpServiceInterceptor,
    },
  ],
})
export class AppModule {}
like image 150
Kaiwen Luo Avatar answered Apr 01 '26 08:04

Kaiwen Luo


I'm not sure if this will help you, but maybe if you get the header from the controller and put it in your services function...

// Controller:

@Get()
getAll(@Request() req){
    const header = req.headers;
    return this._zoneService.sendToHttp(header);
}

Maybe microservices can be better ?

like image 25
nseaprotector Avatar answered Apr 01 '26 10:04

nseaprotector



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!