How to pass api key as query string on request url using passport and nestjs

2.7k Views Asked by At

I have developed api-key strategy following https://www.stewright.me/2021/03/add-header-api-key-to-nestjs-rest-api/

and it works, I pass api-key in header and it authorize it.

Now for some cases I need to pass api-key as query params to url instead of header. I wasn't able to figure it out.

example mysite.com/api/book/5?api-key=myapikey

my current code is

api-key-strategy.ts

@Injectable()
export class ApiKeyStrategy extends PassportStrategy(Strategy, 'api-key') {
    constructor(private configService: ConfigService) {
        super({ header: 'api-key', prefix: '' }, true, async (apiKey, done) =>
            this.validate(apiKey, done)
        );
    }

    private validate(apiKey: string, done: (error: Error, data) => any) {
        if (
            this.configService.get(AuthEnvironmentVariables.API_KEY) === apiKey
        ) {
            done(null, true);
        }
        done(new UnauthorizedException(), null);
    }
}

api-key-auth-gurad.ts

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class ApiKeyAuthGuard extends AuthGuard('api-key') {}

app.controller

...
    @UseGuards(ApiKeyAuthGuard)
    @Get('/test-api-key')
    testApiKey() {
        return {
            date: new Date().toISOString()
        };
    }
...
1

There are 1 best solutions below

1
On BEST ANSWER

I found a solution in case someone else has same problem.

I added canActivate method to my guard, then read the api key from request.query, and add it to header. Then the rest of code is working as before and checking header

@Injectable()
export class ApiKeyAuthGuard extends AuthGuard('api-key') {

    canActivate(context: ExecutionContext) {
        const request: Request = context.switchToHttp().getRequest();
        if (request && request.query['api-key'] && !request.header('api-key')) {
            (request.headers['api-key'] as any) = request.query['api-key'];
        }
        return super.canActivate(context);
    }
}