[英]Guard doesn't execute passport startegy in nestJs
I am using nestjs and having an issue with using guards to authenticate a request.我正在使用 nestjs 并且在使用警卫来验证请求时遇到问题。
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException, HttpStatus, Logger } from '@nestjs/common';
import { Strategy } from 'passport-localapikey-update';
import { size } from 'lodash';
import { AuthService } from './auth.service';
@Injectable()
export class ApiKeyStrategy extends PassportStrategy(Strategy, 'localapikey') {
constructor(private readonly authService: AuthService) {
super();
}
async validate(token: string) {
Logger.log('HERE!!!!!!!!!!!!!!', 'ApiKeyStrategy'); // Not printed
const data = await this.authService.authenticateClient(token);
if (!size(data)) {
throw new UnauthorizedException('Unauthorized');
}
return data;
}
}
The @UseGuards(AuthGuard('localapikey'))
doesn't execute and throws 401 error. @UseGuards(AuthGuard('localapikey'))
不执行并抛出 401 错误。
None of the logs are printed.没有打印任何日志。
You have to pass the validation function in the super
constructor of the passport strategy.您必须在通行证策略的
super
构造函数中传递验证函数。
constructor(private readonly authService: AuthService) {
super((token, done) => done(null, this.validate(token)));
}
You can also pass the options object as the first parameter:您还可以将选项对象作为第一个参数传递:
constructor(private readonly authService: AuthService) {
super({apiKeyField: 'myapikeyfield'}, (token, done) => done(null, this.validate(token)));
}
btw: I'd recommend using an instance of Logger
instead of accessing it statically, see this thread .顺便说一句:我建议使用
Logger
的实例而不是静态访问它,请参阅此线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.