如何使用passport和nestjs将api密钥作为请求url上的查询字符串传递

Rez*_*eza 0 passport.js nestjs nestjs-passport

我按照https://www.stewright.me/2021/03/add-header-api-key-to-nestjs-rest-api/制定了 api-key 策略

它有效,我在标头中传递 api-key 并对其进行授权。

现在,对于某些情况,我需要将 api-key 作为查询参数传递给 url 而不是 header。我无法弄清楚。

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

我当前的代码是

api-密钥策略.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);
    }
}

Run Code Online (Sandbox Code Playgroud)

api-key-auth-gurad.ts

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

@Injectable()
export class ApiKeyAuthGuard extends AuthGuard('api-key') {}
Run Code Online (Sandbox Code Playgroud)

应用程序控制器

...
    @UseGuards(ApiKeyAuthGuard)
    @Get('/test-api-key')
    testApiKey() {
        return {
            date: new Date().toISOString()
        };
    }
...
Run Code Online (Sandbox Code Playgroud)

Rez*_*eza 5

我找到了解决方案,以防其他人遇到同样的问题。

我将 canActivate 方法添加到我的防护中,然后从 request.query 读取 api 密钥,并将其添加到 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);
    }
}

Run Code Online (Sandbox Code Playgroud)