Home > Software design >  How to create a custom error message for Authorize attribute?
How to create a custom error message for Authorize attribute?

Time:03-31

I want only admins to have access to this controller and its actions, so I've written this code:

[Authorize(Roles = Helper.AdminRole)]
public class AdminController : Controller
{
    public IActionResult AdminPanel()
    {
        return View();
    }
    //other actions only available to admins
}

If the user is not logged in and he's not in the specified role I get a 404 Not Found page and this in the URL:

..../AccessDenied?ReturnUrl=/Admin/AdminPanel

How can I make a custom error page for this scenario where the user is asked to log in so he can confirm his role, and when he does log in successfully AND he is in the right role to be redirected to where he wanted to go, but if his role is invalid to be redirected elsewhere/ shown a custom error page?

CodePudding user response:

Take cookie authentication as an example, you can configure it like this:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(x =>
    {
        //When user doesn't login and he access to an action with [Authorize],
        //He will redirect to the loginPath
        
        x.LoginPath = "/account/login";

        //When user has loged in but the role is not the specified role,
        //He will redicet to the AccessDeniedPath,
        //Then you can custom your own error page

        x.AccessDeniedPath = "/account/error";
    });

CodePudding user response:

Your error was caused due to lack of Loginpath settings,not wrong role or password.(So the error code was 404 not 401)

You could see the test Result:enter image description here

If you want to custom error page,you could read the official document: enter image description here

  • Related