【问题标题】:Nestjs:validate function not working with jwtNestjs:验证功能不适用于 jwt
【发布时间】:2023-03-25 03:20:01
【问题描述】:

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

当我在邮递员中请求时,我没有任何日志,似乎没有进入这个验证功能。:

this is Complete code

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

【问题讨论】:

    标签: node.js typescript jwt nestjs


    【解决方案1】:

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

    1. 令牌已使用您的密钥签名
    2. 令牌未过期
    3. 自定义负载验证

    您可以使用jwt debugger 手动检查您的令牌的步骤 1 和 2。

    【讨论】:

    • 谢谢,我找到原因了,在这里"ExtractJwt.fromAuthHeaderWithScheme('jwt')",“jwt”是小写的,但是“JWT”在header Authorization中是大写的,这很傻错误。
    • 是的,总是需要几个小时才能解决这些愚蠢的小问题。很高兴它现在可以工作了。 :) 欢迎来到stackoverflow! :)
    猜你喜欢
    • 2020-01-07
    • 1970-01-01
    • 2021-04-13
    • 2021-11-03
    • 2018-10-06
    • 2016-11-11
    • 2019-03-28
    • 2021-02-09
    • 1970-01-01
    相关资源
    最近更新 更多