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

问题描述

我根据 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-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') {}

应用程序控制器

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

解决方法

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

我向我的守卫添加了 canActivate 方法,然后从 request.query 读取 api 密钥,并将其添加到标题中。然后其余的代码像以前一样工作并检查标题

@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);
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...