简体   繁体   中英

.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:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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