ASP.NET Core 更改 AccessDenied 路由

Posted

技术标签:

【中文标题】ASP.NET Core 更改 AccessDenied 路由【英文标题】:ASP.NET Core change AccessDenied route 【发布时间】:2017-01-08 01:59:55 【问题描述】:

我在路由 AccessDenied 时遇到了一些问题,也可能是登录/注销路径。该项目是一个没有更多魔法的剥离默认项目。所以存在一个带有AccessDenied() 方法的Account 控制器。

我现在正在尝试的是(这是互联网商品提供的解决方案)

services.Configure<CookieAuthenticationOptions>(options =>

    options.LoginPath = new PathString("/");
    options.AccessDeniedPath = new PathString("/InactiveSponsor");
    options.LogoutPath = new PathString("/");
);

但这绝对没有区别。那么有什么想法吗?关于它为什么不起作用以及如何使它起作用的任何想法。

这是我的 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?");
    );

【问题讨论】:

能发Configure方法代码吗?可能你覆盖了CookieAuthenticationOptions @ademcaglin 添加了整个启动 【参考方案1】:

试试

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

或者

        services.Configure<IdentityOptions>(opt =>
        
            opt.Cookies.ApplicationCookie.LoginPath = new PathString("/aa");
            opt.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/InactiveSponsor");
            opt.Cookies.ApplicationCookie.LogoutPath = new PathString("/");
        );

【讨论】:

有人得到这个解决方案来使用 IdentityServer4 吗?【参考方案2】:

对于 ASP.NET Core 2.x Web 应用中的类似问题,如果使用 Azure AD /OpenID Connect 进行身份验证,您可以通过这种方式更改路由。

services.AddAuthentication(options =>...)
            .AddOpenIdConnect(options =>...)
            .AddCookie(options =>
            
                options.AccessDeniedPath = "/path/unauthorized";
                options.LoginPath = "/path/login";
            );

【讨论】:

干杯!那是美丽的【参考方案3】:

如果有人在 ASP.NET Core 2 中遇到类似问题,您可以将 services.Configure&lt;CookieAuthenticationOptions&gt;(...) 替换为 services.ConfigureApplicationCookie(),如下所示:

在您的 Startup.cs 中替换它:

services.Configure<CookieAuthenticationOptions>(options =>

    options.LoginPath = new PathString("/[your-path]");
    options.AccessDeniedPath = new PathString("/[your-path]");
    options.LogoutPath = new PathString("/[your-path]");
);

用这个:

services.ConfigureApplicationCookie(options =>

    options.LoginPath = new PathString("/[your-path]");
    options.AccessDeniedPath = new PathString("/[your-path]");
    options.LogoutPath = new PathString("/[your-path]");
);

【讨论】:

ConfigureApplicationCookie 是 ASP.NET Identity 的一部分,如果您不使用 ASP.NET Identity(例如我,我使用的是没有 ASP.NET Identity 的 IdentityServer4),那么这些方法都不是工作。

以上是关于ASP.NET Core 更改 AccessDenied 路由的主要内容,如果未能解决你的问题,请参考以下文章

更改 ASP.Net Core 5 中的默认页面

ASP .NET Core 更改默认 ApiController BadResponse

ASP.NET Core 更改 AccessDenied 路由

在 Docker (ASP.NET Core) 中更改时区

在 Asp.Net Core 应用程序中更改默认页面

更改 ASP.NET Core 中 DateTime 解析的默认格式