redirect - NestJS - 检查失败时将用户从 guard 重定向

标签 redirect 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: {},
    };
}

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

最佳答案

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

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 {};
}

关于redirect - NestJS - 检查失败时将用户从 guard 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53869978/

相关文章:

regex - 将旧域重定向到新域的主页

php - 重定向到页面并发送自定义 HTTP header

php - 重定向脚本PHP

javascript - Nest Js TypeORM repository.update 方法不更改对象的多个字段

c# - 重定向到操作并传递引用类型

apache - 使用 apache 后端在 varnish 中缓存重定向

javascript - NestJS/TS 中的依赖 hell

javascript - NestJS 和 GraphQL - TypeError : graphql_1. parse is not a function with minimal setup

nestjs - 在 nest.js e2e 测试中覆盖单个测试中的提供者

typescript - takeUntil 带过滤器