node.js - Nestjs:验证功能不适用于 jwt
问题描述
我正在尝试在下面的文档中使用 jwt
一切正常,但验证功能在 jwt.strategy.ts 中不起作用
这是我的 jwt.strategy.ts:
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from './auth.service';
import { JwtPayload } from './interfaces/jwt-payload.interface';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('JWT'),
secretOrKey: 'secretKey',
});
}
async validate(payload: JwtPayload) {
console.log(payload)
// const user = await this.authService.validateUser(payload);
// if (!user) {
// throw new UnauthorizedException();
// }
// return user;
}
}
auth.module.ts:
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: 'secretKey',
signOptions: {
expiresIn: 3600,
},
}),
],
providers: [AuthService, JwtStrategy],
})
export class AuthModule {}
app.module.ts:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserModule } from './user/user.module';
import { GraphQLModule } from '@nestjs/graphql';
import { AuthModule } from './auth/auth.module';
@Module({
imports: [
TypeOrmModule.forRoot(),
GraphQLModule.forRoot({
typePaths: ['./**/*.graphql'],
}),
AuthModule,
UserModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
当我在邮递员中请求时,我没有任何日志,它似乎没有进入这个验证功能。:
对不起,我的英语不好,这是我第一次使用stackoverflow,谢谢你的帮助
解决方案
仅当令牌已根据加密验证(在您的情况下使用正确的密钥对其进行签名)并且未过期时,才会调用validate
您的方法。只有在检查了这两件事之后,才会使用有效负载调用。有了它,您就可以检查用户是否仍然存在。所以这三个步骤是:JwtStrategy
secretKey
validate
- 令牌已使用您的密钥签名
- 令牌未过期
- 自定义有效负载验证
您可以使用jwt 调试器为您的令牌手动检查步骤 1 和 2。
推荐阅读
- kubernetes - 使用查看器将 Tensorboard 集成到 KUBEFLOW 管道中
- php - 如何在 woocommerce 产品页面上拉入 sku?
- sql - 如何只找到最早的日期
- powershell - 如何在构建工件中引用文件
- html - 基于 viewmodel 属性的 Razor 视图禁用 html 属性
- php - 如何在 PHP 上使用 PECL 安装 OpenCensus 扩展
- java - 在 Spring Batch 中实现容错
- node.js - 我可以自定义字段名称 collection.group mongodb
- reactjs - 输入文件上传api平台无效
- firebase - 在没有 Google 帐户的情况下登录 Google Cloud Endpoints 门户页面