【发布时间】:2021-05-13 05:49:26
【问题描述】:
我已关注此guide,试图让 JWT 身份验证正常工作。
我唯一的区别是我将 JWT 令牌保留在 HttpOnly cookie 中,这意味着需要自定义提取器。
我找到了一个example ,介绍了如何从 cookie 中提取令牌。所以,唯一的区别是:
jwtFromRequest: ExtractJwt.fromExtractors([(req: Request) => {
return req?.cookies?.access_token
}])
很遗憾,req 是 undefined 没有明显的原因。
这就是我的 auth.module.ts 的样子:
@Module({
imports: [
PassportModule,
JwtModule.register({
secret: 'qweqweqweqeqwe',
signOptions: { expiresIn: '20s' }
})
],
providers: [
AuthService,
AuthResolver,
JwtAuthGuard,
JwtStrategy
]
})
export class AuthModule { }
我还创建了一个策略文件jwt.stragegy.ts:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromExtractors([(req: Request) => {
return req?.cookies?.access_token
}]),
ignoreExpiration: false,
secretOrKey: 'qweqweqweqeqwe',
})
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username }
}
}
auth.guard.ts:
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
这可能是 passport.js 库方面的错误吗? 就像,@nestjs/passport 无法映射参数或其他东西......
【问题讨论】:
-
你确定
req是什么undefined?您是否安装了 cookie-parser 中间件? -
@JayMcDoniel 绝对是。此外,当打印
arguments时——长度为 0。关于 cookie-parser——它已被激活,在其他地方我什至可以访问我的 cookie。app.use(cookieParser())就是这样。
标签: node.js jwt passport.js nestjs passport-jwt