我使用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错误。
日志中没有被打印。
你必须通过验证功能的护照战略super
构造。
constructor(private readonly authService: AuthService) {
super((token, done) => done(null, this.validate(token)));
}
您也可以通过选择对象作为第一个参数:
constructor(private readonly authService: AuthService) {
super({apiKeyField: 'myapikeyfield'}, (token, done) => done(null, this.validate(token)));
}
BTW:我建议你使用Logger
的一个实例,而不是静态地访问它,请参阅this thread。