Reputation: 73
I use the TransformAsync(ClaimsPrincipal principal)
method to add a Role
var c = new Claim(currentUser.RoleClaimType, "Admin");
currentUser.AddClaim(c);
in my controler:
[Authorize(Roles = "Admin")]
but if the user doesn't have the admin role => access denied to this page 403
My question is:
how can I redirect to a custom error page if authorization failed?
Upvotes: 0
Views: 790
Reputation: 73
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
using System;
namespace HZZNKZ10Upisnik.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
Solution is to add in Startup.cs
this code in Configure
method:
app.UseStatusCodePages(async context => {
var response = context.HttpContext.Response;
if (response.StatusCode == (int)HttpStatusCode.Forbidden)
{
response.Redirect("/Home/Error");
}
});
app.UseStatusCodePages(async context => {
var response = context.HttpContext.Response;
if (response.StatusCode == (int)HttpStatusCode.NotFound)
{
response.Redirect("/Home/NotFound");
}
});
In Views/Shared folder you can than modify or add your Error.cshtml and add NotFound.cshtml page which is using your Error View Model in header section (if you need it...) or you can just use plain HTML to define your error.
Upvotes: 1
Reputation: 1
Throwing an exception in the requirement handler with the info necessary and then handling the error in the ErrorHandlingMiddleware.
that's the only solution i found when you want to control the response and response code by the error in the policy.
Upvotes: 0