Nabil Dendane
Nabil Dendane

Reputation: 73

how change access denied if Authorize Attribute failed in Asp.net Core 3.1? redirect custom error page

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

Answers (2)

Nabil Dendane
Nabil Dendane

Reputation: 73

Add to Home Controller (you probably already have this)

 [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

Error View Model (you probably already have this)

using System;

namespace HZZNKZ10Upisnik.Models
{
    public class ErrorViewModel
    {
        public string RequestId { get; set; }

        public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
    }
}

Handling 403 errors (AccessDenied)

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");
                }

            });

Handling 404 errors (Page not found)

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

TCDooM
TCDooM

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

Related Questions