node.js - Nestjs:验证函数不适用于 jwt

标签 node.js typescript jwt nestjs

我正在尝试在 document 之后的 nest 中使用 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 {}

应用程序模块.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 {}

当我在 postman 中请求时,我没有任何日志,它似乎没有进入此验证功能。:

enter image description here

this is Complete code

对不起,我的英语不好,这是我第一次使用stackoverflow,感谢您的帮助

最佳答案

JwtStrategyvalidate 方法只会在 token 已通过加密验证时调用(在您的情况下,使用正确的 key 对其进行签名secretKey) 且未过期。只有在检查了这两件事之后,才会使用有效负载调用 validate。有了它,您就可以例如检查用户是否仍然存在。所以这三个步骤是:

  1. token 已用您的 key 签名
  2. token 未过期
  3. 自定义负载验证

您可以使用 jwt debugger手动检查您的 token 的第 1 步和第 2 步。

关于node.js - Nestjs:验证函数不适用于 jwt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54265304/

相关文章:

node.js - node-mysql2:结果集未反射(reflect)最新结果

node.js:将 ObjectId 数组与字符串对象 id 或字符串 ObjectId 数组进行比较

javascript - 前端 : underscore. js 或 async.js 通过 browserify?

javascript - 通过每个索引上的特定属性是否为真来正确过滤对象数组的可观察对象?

javascript - 如何在测试文件中包含 Typescript 命名空间?

json - 用户权限更改后 JWT 刷新

authentication - ASP.NET Core 是否支持刷新 token ?

javascript - javascript for循环中的异步函数

javascript - 开关大小写 typescript 大小写不适用于字符串

node.js - 带有 Passport 的 Sails.js 中的 JWT