Nest js passport AuthGuard 未验证有效令牌,返回“401 未授权”

问题描述 投票:0回答:0

使用策略生成令牌有效,令牌可使用 JwtService validate(token) 验证,但是当我尝试使用 @UseGuards(AuthGuard) 时,它返回“401 Unauthorized”

这是我的代码:

auth.guard.ts:

import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { GqlExecutionContext } from '@nestjs/graphql';

@Injectable()
export class JwtUserAuthGuard extends AuthGuard('user-jwt') {
  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
  }
}

jwt.strategy.ts:

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class UserJwtStrategy extends PassportStrategy(Strategy, 'user-jwt') {
  constructor(private readonly configService: ConfigService, private readonly jwtService: JwtService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('USER_AUTH_JWT_ACCESS_TOKEN_PUBLIC_KEY'),
      algorithms: ['RS256']
    });
  }

  async validate(payload: any) {
    return {
      sub: payload.sub,
      email: payload.email,
      role: payload.role,
      loginHistoryId: payload.loginHistoryId
    };
  }

  async validateByToken(token: string) {
    return this.validate(this.jwtService.decode(token));
  }
}

auth.module.ts:

 JwtModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        privateKey: configService.get<string>('USER_AUTH_JWT_ACCESS_TOKEN_PRIVATE_KEY'),
        publicKey: configService.get<string>('USER_AUTH_JWT_ACCESS_TOKEN_PUBLIC_KEY'),
        signOptions: {
          algorithm: 'RS256'
        }
      }),
      inject: [ConfigService]
    })
  ],
  providers: [UserJwtStrategy]

user.resolver.ts:

  @UseGuards(JwtUserAuthGuard)
  @Query(() => User)
  async getUserProfile(@Args('data') data: GetUserInput, userId: number) {
    const user = await this.usersService.getUserProfile(data, userId);
    if (!user) {
      throw new NotFoundException('USER_NOT_FOUND');
    }
    console.log('user', user);
    return user;
  }

当我

m rty to login it works well, user passes all validations and gets a valid tokens, but when i
我尝试使用 AuthGuard 时,它返回“401 Unauthorized”,有人知道我该如何解决它吗?

jwt nestjs authorization passport-jwt
© www.soinside.com 2019 - 2024. All rights reserved.