【发布时间】:2020-08-19 17:34:56
【问题描述】:
我正在尝试使用nestJS 了解jwt 和身份验证。 我创建了两个独立的微服务,其中一个是身份验证服务,成功登录后,客户端获取 jwt 令牌,并使用此令牌可以访问另一个微服务。
这里是auth服务的JwtStrategy和AuthModule的代码:
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'secretKey'
});
}
async validate(payload: any) {
return payload;
}
}
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { UsersModule } from '../users/users.module';
import { PassportModule } from '@nestjs/passport';
import { LocalStrategy } from './local.strategy';
import { JwtStrategy } from './jwt.strategy';
import { JwtModule } from '@nestjs/jwt';
import { jwtConstants } from './constants';
import { AuthController } from './auth.controller';
import * as fs from 'fs';
@Module({
imports: [
UsersModule,
PassportModule,
JwtModule.register({
secret: 'secretKey',
signOptions: { expiresIn: '1h' },
}),
],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService],
controllers: [AuthController],
})
export class AuthModule {}
这是另一个服务的代码:
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'secretKey',
});
}
async validate(payload: any) {
return payload;
}
}
我发现对两个服务使用相同的密钥是没有意义的(因为如果我要创建 10 个微服务,我不会对所有微服务使用相同的密钥)所以我创建了一个私有和公共使用 openssl 的密钥。 在 AuthModule 中,我复制了私钥而不是“secretKey”字符串,在其他服务中,我复制了公钥而不是“secretKey”字符串,但我收到了 401,未经授权的错误。 我在这里错过了什么?为什么 JwtStrategy 不验证公钥?
【问题讨论】:
标签: authentication jwt passport.js nestjs jwt-auth