我正在使用nestjs,并且在使用警卫来验证请求时遇到问题。

Gist (full code)

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)));
}




您还可以将options对象作为第一个参数传递:

constructor(private readonly authService: AuthService) {
  super({apiKeyField: 'myapikeyfield'}, (token, done) => done(null, this.validate(token)));
}




顺便说一句:我建议使用Logger实例,而不是静态访问它,请参见this thread

关于javascript - Guard在nestJs中不执行 Passport 策略,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54573033/

10-09 17:20