首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在NestJS中使用jwt策略链?

如何在NestJS中使用jwt策略链?
EN

Stack Overflow用户
提问于 2022-06-16 18:42:35
回答 1查看 492关注 0票数 0

在我的nestjs项目中,我尝试使用多个jwt策略。以下是jwt-Auth.Guard d.ts:

代码语言:javascript
运行
复制
export class JwtAuthGuard extends AuthGuard(['jwt', 'sec']) {}

jwt.strategy.ts:

代码语言:javascript
运行
复制
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: ‘test’,
    });
  }
  async validate(payload: any) {
    return {
      userId: payload.sub,
      username: payload.username,
    };
  }
}

sec.strategy.ts:

代码语言:javascript
运行
复制
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategysec extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: '1test',
    });
  }
  async validate(payload: any) {
    return {
      userId: payload.sub,
      username: payload.username,
    };
  }
}

Auth.module.ts:

代码语言:javascript
运行
复制
@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: 'test',
      signOptions: { expiresIn: '2000000s' },
    }),
  ],
  providers: [
    AuthService,
    LocalStrategy,
    JwtStrategysec,
    JwtStrategy,
  ],
  exports: [AuthService, JwtModule],
})
export class AuthModule {}

当我试图在代码中使用JwtAuthGuard时:

代码语言:javascript
运行
复制
  @UseGuards(JwtAuthGuard)

我可以得到错误:

代码语言:javascript
运行
复制
 ERROR [ExceptionsHandler] Unknown authentication strategy "sec"

我是不是漏掉了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-16 19:10:21

在您的sec.strategy.ts中,您需要给策略一个定制名称,如下所示:

代码语言:javascript
运行
复制
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategysec extends PassportStrategy(Strategy, 'sec') {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: '1test',
    });
  }
  async validate(payload: any) {
    return {
      userId: payload.sub,
      username: payload.username,
    };
  }
}

否则,它将采用默认的'jwt'名称。有了上面这些,现在它就有了'sec'的名字,并且用护照进行了适当的注册

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72650537

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档