2

Problem: Whenever normal user attempts to access pages that are only accessible by administrators, user is always redirected to login instead of access denied page.

Question: How can the normal user see the access denied page whenever the user access restricted pages?

Controller:

[Authorize(Roles = "Administrator")]
public class AdminOnlyController: Controller{

}

Startup.cs

app.UseIdentity();

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
            AuthenticationScheme = "FirstCookieAuthentication",
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            AccessDeniedPath = new PathString("/Forbidden/"),
            LoginPath = new PathString("/Conotroller/Login"),
});
Captain Neff
  • 33
  • 1
  • 8

2 Answers2

0

Access denied is just a status code like not found, internal error etc. To manage status codes you can use middleware "app.UseStatusCodePages".

Code:

if (env.IsDevelopment())
{
//       see something more here
}
else
{
        app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");
}

then inside StatusCodeController, build an action result that matches the route you provided, ex:

    [HttpGet("/StatusCode/{statusCode}")]
    public IActionResult Index(int statusCode)
    {
        string statusmessage = "";
        switch (statusCode)
        {
            case 400:
                statusmessage = "Bad request: The request cannot be fulfilled due to bad syntax";
                break;
            case 403:
                statusmessage = "Forbidden";
                break;
//all codes here...
            default:
                statusmessage = "That’s odd... Something we didn't expect happened";
                break;
        }

        // return appropriate view 
        // or same view with different message, eg from ViewBag
    }
Ermir Beqiraj
  • 847
  • 10
  • 23
  • uhmm i checked the response status code and it always return 200 even if I as the normal user, access restricted pages. – Captain Neff Sep 15 '17 at 07:44
0

What I did is created a custom Attribute which implements IActionFilter interface and inherits Attribute class. So basically I put my code inside On Action Executing Method. However I've also read this thread about not creating custom attribute. But I didn't read the whole discussion there in the comment section. Anyway this works for my case.

Captain Neff
  • 33
  • 1
  • 8