【问题标题】:Customise the response on verification failure for a jwt Strategy NestJs自定义 jwt 策略 NestJs 验证失败的响应
【发布时间】:2020-05-19 09:26:33
【问题描述】:

我成功实现了一个使用nestJs进行身份验证的jwt策略。

下面是jwt策略的代码

import { ServerResponse } from './../helpers/serverResponse.helper';
import { Injectable, UnauthorizedException, HttpStatus } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { config as env } from 'dotenv';
import { Bugsnag } from '../helpers/bugsnag.helper';

env();

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
    constructor(
    private readonly logger: Bugsnag,
    ) {
    super({
        jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
        secretOrKey: process.env.JWT_SECRET_KEY,
        passReqToCallback: true,
    });

    }

    async validate(payload, done: Function) {
    try {
        const validClaims = await this.authService.verifyTokenClaims(payload);

        if (!validClaims)
            return done(new UnauthorizedException('invalid token claims'), false);
        done(null, payload);
    } catch (err) {
        this.logger.notify(err);
        return ServerResponse.throwError({
        success: false,
        status: HttpStatus.INTERNAL_SERVER_ERROR,
        message: 'JwtStrategy class, validate function',
        errors: [err],
        });
    }
    }
}

我看到here 仅当请求标头中提供了有效令牌时才会调用验证函数,我对此表示同意。但是,我想知道是否可以自定义在这种情况下发送的响应对象(提供的令牌无效)。

如果是,我该怎么做?

【问题讨论】:

    标签: authentication jwt nestjs passport-jwt


    【解决方案1】:

    您可以使用exception filter 捕获UnauthorizedExceptions 并根据需要修改那里的响应。另一种选择是扩展AuthGuard('jwt') mixin 类并在try/catch 周围为super.canActivate(context) 添加一些逻辑,然后在错误中阅读原因是什么,并在您的自定义消息中抛出一个特定的UnauthorizedException

    【讨论】:

    • 谢谢@jay McDoniel。异常过滤器很好地解决了这个问题
    【解决方案2】:

    您可以使用AuthGuard('jwt')handleRequest 方法在JWT 验证失败时抛出任何异常。

    @Injectable()
    export class JwtAuthGuard extends AuthGuard('jwt') {
      handleRequest(err: any, user: any, info: any, context: any, status: any) {
        if (info instanceof JsonWebTokenError) {
          throw new UnauthorizedException('Invalid Token!');
        }
    
        return super.handleRequest(err, user, info, context, status);
      }
    }
    

    JsonWebTokenError来自jsonwebtoken库,供passport内部使用。

    【讨论】:

      猜你喜欢
      • 2018-02-18
      • 2016-09-17
      • 2018-03-02
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 2020-04-20
      • 2017-09-21
      相关资源
      最近更新 更多