我不能在这里传递任何秘密,因为它为每个用户存储在 Redis 中,我必须先解析令牌主体,然后才能访问用户 ID 以获取他们的秘密。使用 nestjs 进行架构。是否有任何优雅的解决方案,而无需自己编写整个策略副本?
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: ???,
passReqToCallback: true,
});
}
async validate(req: any, payload: UserType): Promise<UserType> {
try {
const token = ExtractJwt.fromAuthHeaderAsBearerToken()(req);
const [header, body] = token.split('.');
const headerJSON = JSON.parse(btoa(header)) as { alg: Algorithm };
const bodyJSON = JSON.parse(btoa(body)) as UserType;
const sub = bodyJSON.sub;
const userId = await this.authService.findUserSecret(sub);
const jwt = new JwtService({
secret: userId,
});
await jwt.verify(token, {
algorithms: [headerJSON.alg],
});
return payload;
} catch (e) {
return Promise.reject();
}
}
}```