passport.js - 如何使用护照和nestjs将api密钥作为请求url上的查询字符串传递
问题描述
我按照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 密钥,并将其添加到 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);
}
}
推荐阅读
- airflow - 指定一组气流任务在其他任务之前运行的方法(顺序不变)?
- python - 为什么用于展平 n 维可迭代列表的“for for”习语有效?
- android - 键盘只允许底页打开一半
- python - 在 python pandas 中合并数据的问题
- webpack - Webpack:将 JS 转换为 SASS 和 CSS
- c++ - C++ 内联构造函数和符号表
- javascript - 如何通过点击自动推进项目?
- java - 根据嵌套字段对 JSON 数据进行排序
- python - 类方法不会从另一个模块相互调用
- github-actions - Github Actions:如何在脚本中使用策略/矩阵