在我的 nestjs 專案中,我正在嘗試使用多種 jwt 策略。這是 jwt-auth.guard.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"
我在這里錯過了什么嗎?
uj5u.com熱心網友回復:
在你的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://www.uj5u.com/houduan/492155.html
