在我的nestjs项目中,我尝试使用多个jwt策略。以下是jwt-Auth.Guard d.ts:
export class JwtAuthGuard extends AuthGuard(['jwt', 'sec']) {}
jwt.strategy.ts:
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:
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:
@Module({
imports: [
UsersModule,
PassportModule,
JwtModule.register({
secret: 'test',
signOptions: { expiresIn: '2000000s' },
}),
],
providers: [
AuthService,
LocalStrategy,
JwtStrategysec,
JwtStrategy,
],
exports: [AuthService, JwtModule],
})
export class AuthModule {}
当我试图在代码中使用JwtAuthGuard时:
@UseGuards(JwtAuthGuard)
我可以得到错误:
ERROR [ExceptionsHandler] Unknown authentication strategy "sec"
我是不是漏掉了什么?
发布于 2022-06-16 19:10:21
在您的sec.strategy.ts
中,您需要给策略一个定制名称,如下所示:
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'
的名字,并且用护照进行了适当的注册
https://stackoverflow.com/questions/72650537
复制相似问题