【发布时间】:2021-08-20 17:38:27
【问题描述】:
我已经按照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') {}
app.controller
...
@UseGuards(ApiKeyAuthGuard)
@Get('/test-api-key')
testApiKey() {
return {
date: new Date().toISOString()
};
}
...
【问题讨论】:
标签: passport.js nestjs nestjs-passport