NestJS-检查失败时重定向用户 [英] NestJS - Redirect user from guard when check fails
本文介绍了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 false
替换为response.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 {};
}
这篇关于NestJS-检查失败时重定向用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文