最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

卫兵不执行nestJs护照策略

运维笔记admin10浏览0评论

卫兵不执行nestJs护照策略

卫兵不执行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错误。

日志中没有被打印。

回答如下:

你必须通过验证功能的护照战略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。

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论