Saturday, September 7, 2019

Change AccessDenied route in ASP.NET Core

We will discuss how to change the default AccessDenied route in ASP.NET Core

Default AccessDenied Route in ASP.NET Core

In ASP.NET Core if we try to access an unauthorized resource, by default we are redirected to /Account/AccessDenied path.


Change Default AccessDenied Route

To change the default access denied route, modify the code in ConfigureServices() method of the Startup class

public void ConfigureServices(IServiceCollection services)
{
    services.ConfigureApplicationCookie(options =>
    {
        options.AccessDeniedPath = new PathString("/Administration/AccessDenied");
    });
}

With the above change in place, if we try to access an unauthorized resource, we will be redirected to /Administration/AccessDenied path. Our obvious next step is to include AccessDenied action in the Administration controller and the corresponding view.

AccessDenied Action

[HttpGet]
[AllowAnonymous]
public IActionResult AccessDenied()
{
    return View();
}

AccessDenied View

<div class="text-center">
    <h1 class="text-danger">Access Denied</h1>
    <h6 class="text-danger">
        You do not have persmission to view this resource
    </h6>
    <img src="~/images/noaccess.png" style="height:300pxwidth:300px" />
</div>

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...