Asp.net

ASP.NET Core 更改 AccessDenied 路由

  • December 29, 2020

我在路由 AccessDenied 時遇到了一些問題,也可能是登錄/註銷路徑。該項目是一個沒有更多魔法的剝離預設項目。所以存在一個Account帶有AccessDenied()方法的控制器。

我現在正在嘗試的是(這是網際網路商品提供的解決方案)

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?}");
   });
}

嘗試

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("/");
       });

對於 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";
           });

引用自:https://stackoverflow.com/questions/39250272