我在我正在构建的 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 {};
}
关于redirect - NestJS - 检查失败时将用户从 guard 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53869978/