警卫队未在nestJs中执行护照保护

时间:2019-02-07 12:09:07

标签: javascript node.js typescript passport.js nestjs

我正在使用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错误。

未打印任何日志。

1 个答案:

答案 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