How can i display an error page on ASP.NET Core when using [Authorize]
attribute?
Policy
services.AddAuthorization(p =>
{
p.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
p.AddPolicy("RequireTrainerRole", policy => policy.RequireRole("Trainer"));
p.AddPolicy("RequireTeamLeaderRole", policy => policy.RequireRole("Team Leader"));
p.AddPolicy("RequireUserRole", policy => policy.RequireRole("User"));
});
Controller
[Authorize(Policy = "RequireAdminRole")]
[Area("Admin")]
public class BaseController : Controller
{
}
If you use cookie authentication to protect your resources then you could use AccessDeniedPath
property to redirect to error page:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AccessDeniedPath = "<path>"
});
Otherwise you can handle 403 with using UseStatusCodePages
app.UseStatusCodePages(new StatusCodePagesOptions()
{
HandleAsync = (ctx) =>
{
if (ctx.HttpContext.Response.StatusCode == 403)
{
//handle
}
return Task.FromResult(0);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With