简体   繁体   English

.NET Core AuthorizationHandler 失败 - 如何路由到新页面

[英].NET Core AuthorizationHandler fails - how to route to a new page

So the idea is I check if the user session is still valid and other verifications of the user.所以我的想法是检查用户会话是否仍然有效以及用户的其他验证。 It works fine for passes but if it fails, it means the user session has expired and I want to route the user to the Login page.它适用于通行证,但如果失败,则意味着用户会话已过期,我想将用户路由到登录页面。

在此处输入图像描述

You can try to redirect to any desired controller action using the AuthorizationFilterContext and with the RedirectToActionResult:您可以尝试使用 AuthorizationFilterContext 和 RedirectToActionResult 重定向到任何所需的控制器操作:

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasPermissionRequirement requirement)
{
    // Get the context       
    var redirectContext = context.Resource as AuthorizationFilterContext;
    //check the condition 
    if (!result)
    {
        redirectContext.Result = new RedirectToActionResult("Login", "Account", null);
        context.Succeed(requirement);
        return Task.CompletedTask;
    }
    context.Succeed(requirement);
    return Task.CompletedTask;
}

Or you can try to use a custom middleware to check the authorize result and redirect to the login page, code like this:或者您可以尝试使用自定义中间件检查授权结果并重定向到登录页面,代码如下:

//SET REDIRECTION BASED ON AUTHORIZATION POLICY START
app.Use(async (ctx, next) =>
{
    var ep = ctx.Features.Get<IEndpointFeature>()?.Endpoint;
    var authAttr = ep?.Metadata?.GetMetadata<AuthorizeAttribute>();
    if (authAttr != null && authAttr.Policy == "LoggedIn")
    {
        var authService = ctx.RequestServices.GetRequiredService<IAuthorizationService>();
        var result = await authService.AuthorizeAsync(ctx.User, ctx.GetRouteData(), authAttr.Policy);
        if (!result.Succeeded)
        {
            var path = $"/login";
            ctx.Response.Redirect(path);
            return;
        }
    }
    await next();
});
//SET REDIRECTION BASED ON AUTHORIZATION POLICY END

More detail information, see Redirect to Login when Unauthorized using ASP.NET Core Policy-Based Authorization .更多详细信息,请参阅 使用 ASP.NET Core 基于策略的授权在未授权时重定向到登录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM