我正在使用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;
}
}
@UseGuards(AuthGuard('localapikey'))
无法执行并抛出401错误。
未打印任何日志。
答案 0 :(得分:1)
您必须在护照策略的super
构造函数中传递验证功能。
constructor(private readonly authService: AuthService) {
super((token, done) => done(null, this.validate(token)));
}
您还可以将options对象作为第一个参数传递:
constructor(private readonly authService: AuthService) {
super({apiKeyField: 'myapikeyfield'}, (token, done) => done(null, this.validate(token)));
}
btw:我建议您使用Logger
的实例,而不要静态访问它,请参见this thread。