admin管理员组文章数量:1401785
I'm trying to implement RS256 JWT tokens in nestjs backend. I followed the example provided in nestjs documentation.
In my module I register the JwtModule
with my private key:
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: extractKey(`${process.cwd()}/keys/jwt.private.key`),
signOptions: {
expiresIn: 3600,
},
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy, HttpStrategy],
})
export class AuthModule {}
I'm able to call auth/token endpoint and get the token but when I try to access guarded endpoint I always get 401.
Below you can find my custom JwtStrategy
:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: extractKey(`${process.cwd()}/keys/jwt.public.key`),
});
}
async validate(payload: JwtPayload) {
console.log('JwtStrategy');
const user = await this.authService.validateUser(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
And guarded endpoint:
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Get('token')
async createToken(): Promise<any> {
return await this.authService.createToken();
}
@Get('data')
@UseGuards(AuthGuard())
findAll() {
console.log('Guarded endpoint');
// This route is restricted by AuthGuard
// JWT strategy
}
}
I assume that when I call the auth/data I should see in the console at least the "JwtStrategy" string that I log in the validate method. Unfortunately it never shows up. Why the validate method is never called?
Please find the codesandbox below
I'm trying to implement RS256 JWT tokens in nestjs backend. I followed the example provided in nestjs documentation.
In my module I register the JwtModule
with my private key:
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: extractKey(`${process.cwd()}/keys/jwt.private.key`),
signOptions: {
expiresIn: 3600,
},
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy, HttpStrategy],
})
export class AuthModule {}
I'm able to call auth/token endpoint and get the token but when I try to access guarded endpoint I always get 401.
Below you can find my custom JwtStrategy
:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: extractKey(`${process.cwd()}/keys/jwt.public.key`),
});
}
async validate(payload: JwtPayload) {
console.log('JwtStrategy');
const user = await this.authService.validateUser(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
And guarded endpoint:
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Get('token')
async createToken(): Promise<any> {
return await this.authService.createToken();
}
@Get('data')
@UseGuards(AuthGuard())
findAll() {
console.log('Guarded endpoint');
// This route is restricted by AuthGuard
// JWT strategy
}
}
I assume that when I call the auth/data I should see in the console at least the "JwtStrategy" string that I log in the validate method. Unfortunately it never shows up. Why the validate method is never called?
Please find the codesandbox below
Share Improve this question edited Mar 11, 2019 at 8:23 jmazur asked Mar 10, 2019 at 19:47 jmazurjmazur 1351 gold badge4 silver badges12 bronze badges3 Answers
Reset to default 7You have to specify RS256 as the algorithm for in both the JwtModule
and the JwtStrategy
:
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: publicKey,
algorithms: ['RS256'],
^^^^^^^^^^^^^^^^^^^^^^
});
and
JwtModule.register({
secretOrPrivateKey: privateKey,
signOptions: {
expiresIn: 3600,
algorithm: 'RS256',
^^^^^^^^^^^^^^^^^^^
},
}),
Not sure if it works but you can try this
@UseGuards(AuthGuard('jwt'))
above your protected route.
It's quite possible that the public key and/or private key files were not generated in RS256 format.
I'd remend trying the following:
https://gist.github./ygotthilf/baa58da5c3dd1f69fae9
本文标签: javascriptNestJsPassportJWTStrategy never being called with RS256 tokensStack Overflow
版权声明:本文标题:javascript - NestJs + Passport - JWTStrategy never being called with RS256 tokens - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744288672a2599007.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论