Search code examples
c#asp.net-coreasp.net-core-identity

How to Change Access Denied Route in .Net core


I'm having trouble with Roles and routes I have an Account Controller and I'm using Asp Identity in one of my controllers. It requires a specific Role to access it. The problem is, I want it to redirect the Unauthorized User to the login page "Account/Login" but it is redirecting me to "Account/AccessDenied"

I tried the following but it didn't work

 services.AddIdentity<AppUser, AppRole>(option =>
           {
               option.User.RequireUniqueEmail = true;
               
           }).AddEntityFrameworkStores <AppIdentityDbContext>(); 

And here I'm editing the paths

services
        .AddAuthentication()
        .AddCookie(options =>
        {
            options.LoginPath = "account/login";
            options.LogoutPath = "account/logout";
            options.AccessDeniedPath = "account/login";
            
        });

Here is the Controller

[Authorize(Roles = "admin , secretary")]

Solution

  • You can use

            services.ConfigureApplicationCookie(options =>
            {
    
                options.LoginPath = "/Identity/Account/Login";  //in your case /Account/Login
                options.LogoutPath = "/Identity/Account/logout";
                options.AccessDeniedPath = "/Identity/Account/login";
            });
    
            services.AddAuthentication().AddCookie();
    

    Further, if you are using .net core 1.x, and want to migrate to 2.0 or later, please follow this Microsoft migration article