【问题标题】:Guard doesn't execute passport startegy in nestJsGuard 不在 NestJs 中执行护照策略
【发布时间】:2019-07-01 13:14:36
【问题描述】:

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

不打印任何日志。

【问题讨论】:

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


    【解决方案1】:

    您必须在护照策略的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)));
    }
    

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

    【讨论】:

    • 我注意到当我在“apiKey”键下的标题中传递 api 键时它工作正常。 localapikey 策略允许通过执行“const strat = new LocalApiKeySStrategy(options)”来改变它。我怎么能在这里做到这一点,因为 PassportStrategy 需要对象而不是实例。
    • 我已将您的附加问题的答案添加为编辑。
    • 我查看了nest.js的代码和passport-localapikey-update库。我认为没有文档。 :-|
    猜你喜欢
    • 2022-08-12
    • 1970-01-01
    • 2020-10-21
    • 2020-04-20
    • 2022-11-04
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 2021-01-10
    相关资源
    最近更新 更多