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.