Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core change AccessDenied route

I'm having some trouble with routing AccessDenied, probably Login/Logout path as well. The project is a stripped default one with no more magic. Soo there exist a Account controller with an AccessDenied() method.

What I'm trying now is (this is the solution offered by the goods of the internet)

services.Configure<CookieAuthenticationOptions>(options =>
{
    options.LoginPath = new PathString("/");
    options.AccessDeniedPath = new PathString("/InactiveSponsor");
    options.LogoutPath = new PathString("/");
});

But that does absolutely no difference. So any ideas? Any idea on why don't it work and how to make it work.

Here is my Startup.cs

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();

    if (env.IsDevelopment())
    {
        // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
        builder.AddApplicationInsightsSettings(developerMode: true);
    }
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    string connection = "DefaultConnection";
    //services.AddDbContext<SponsorContext>(options => options.UseSqlServer(connection));
    services.AddDbContext<SponsorContext>(options => options.UseSqlServer(Configuration[$"Data:{connection}"]));

    services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddEntityFrameworkStores<SponsorContext>()
        .AddDefaultTokenProviders();


    services.AddMvc();


    services.AddAuthorization(options =>
    {
        options.AddPolicy(Policies.RequireAdmin, policy => policy.RequireRole(Roles.Administrator));
        options.AddPolicy(Policies.IsSponsor, policy => policy.RequireRole(Roles.Sponsor));
        options.AddPolicy(Policies.IsSponsorOrAdmin, policy => policy.RequireRole(Roles.Administrator, Roles.Sponsor));
    });

    /*
     * AddTransient Different on each instance/use
     * AddScoped Different instance on a per request basis
     * AddSingleton Always the same instance
     */
    //DI
    services.AddScoped<ManageUserRepository>();
    services.AddScoped<ISponsorManagement, SponsorRepository>();
    services.AddScoped<ISponsorRead, SponsorRepository>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseApplicationInsightsExceptionTelemetry();

    app.UseStaticFiles();
    app.UseIdentity();


    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
like image 531
Thomas Andreè Wang Avatar asked Aug 31 '16 12:08

Thomas Andreè Wang


3 Answers

Try

 services.AddIdentity<ApplicationUser, IdentityRole>(op=>op.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/InactiveSponsor"))
         .AddEntityFrameworkStores<SponsorContext>()
         .AddDefaultTokenProviders();

Or

        services.Configure<IdentityOptions>(opt =>
        {
            opt.Cookies.ApplicationCookie.LoginPath = new PathString("/aa");
            opt.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/InactiveSponsor");
            opt.Cookies.ApplicationCookie.LogoutPath = new PathString("/");
        });
like image 147
adem caglin Avatar answered Nov 12 '22 23:11

adem caglin


For similar problems into an ASP.NET Core 2.x web app, if the authentication is made with Azure AD /OpenID Connect, you can change the route in this way.

services.AddAuthentication(options =>...)
            .AddOpenIdConnect(options =>...)
            .AddCookie(options =>
            {
                options.AccessDeniedPath = "/path/unauthorized";
                options.LoginPath = "/path/login";
            });
like image 26
Andrei Avatar answered Nov 12 '22 21:11

Andrei


In case someone experiences similar problems in ASP.NET Core 2, you could replace services.Configure<CookieAuthenticationOptions>(...) with services.ConfigureApplicationCookie() like this:

Replace this in your Startup.cs:

services.Configure<CookieAuthenticationOptions>(options =>
{
    options.LoginPath = new PathString("/[your-path]");
    options.AccessDeniedPath = new PathString("/[your-path]");
    options.LogoutPath = new PathString("/[your-path]");
});

with this:

services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = new PathString("/[your-path]");
    options.AccessDeniedPath = new PathString("/[your-path]");
    options.LogoutPath = new PathString("/[your-path]");
});
like image 13
Stoyan Dimov Avatar answered Nov 12 '22 23:11

Stoyan Dimov