首页 > 解决方案 > NestJS - 检查失败时从守卫重定向用户

问题描述

我在我正在构建的 NestJS 应用程序中添加了一些简单的、有效的登录功能。我现在想阻止已注销用户访问某些路由,所以我添加了一个简单AuthGuard的 ,如下所示;

@Injectable()
export class AuthGuard implements CanActivate {
    public canActivate(
        context: ExecutionContext,
    ): boolean {
        const request = context.switchToHttp().getRequest();
        const response = context.switchToHttp().getResponse();
        if (typeof request.session.authenticated !== "undefined" && request.session.authenticated === true) {
            return true;
        }
        return false;
    }
}

这样做的方式是阻止用户访问应用了防护的路由,但这样做只会显示这个 JSON 响应;

{
    "statusCode": 403,
    "error": "Forbidden",
    "message": "Forbidden resource"
}

我想要的是当守卫失败时将用户重定向到登录页面。我试过用替换return falseresponse.redirect("/auth/login");,虽然它有效,但在控制台中我收到消息

(node:11526) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.

(node:11526) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

因此,尽管它有效,但它似乎并不是最好的解决方案。

顺便说一句,守卫的路线如下:

@Get()
@UseGuards(AuthGuard)
@Render("index")
public index() {
    return {
        user: {},
    };
}

警卫失败后是否有可能正确重定向用户?

标签: redirectnestjs

解决方案


您可以使用保护和过滤器来实现您想要的。通过守卫的未经授权的异常,处理过滤器到重定向的异常。这是一个这样的过滤器:

import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';
import { Response } from 'express';
import { UnauthorizedException } from '@nestjs/common';

@Catch(UnauthorizedException)
export class ViewAuthFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();

    response.status(status).redirect('/admins');
  }
}

下面是如何使用它:

@Get('/dashboard')
@UseGuards(JwtGuard)
@UseFilters(ViewAuthFilter)
@Render('dashboard/index')
dashboard() {
    return {};
}

推荐阅读