【问题标题】:Why is my authorization fallback policy overriding AllowAnonymous为什么我的授权后备策略覆盖 AllowAnonymous
【发布时间】:2022-01-12 00:23:27
【问题描述】:

我向我的 asp.net 核心应用程序添加了一个后备策略,因为我想要求一个特定的角色作为后备,而不仅仅是一揽子授权。

但是,现在具有 AllowAnonymous 属性的页面正在使用我的后备策略,这似乎与文档直接矛盾。 Microsoft 文档说回退策略适用于没有任何授权或 AllowAnonymous 属性的页面。

例如,Razor 页面、控制器或操作方法 [AllowAnonymous][Authorize(PolicyName="MyPolicy")] 使用应用 身份验证属性而不是回退身份验证 政策。

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/secure-data?view=aspnetcore-6.0

我想知道是不是我在 Startup 中的配置有误,但是搜索我没有发现与我的问题类似的东西。

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddDbContext<MyDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("MyDbContext")));
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<MyDbContext>();
    services.AddScoped<MySharedService>();
    services.ConfigureApplicationCookie(options =>
    {
        options.LoginPath = $"/Identity/Account/Login";
        options.LogoutPath = $"/Identity/Account/Logout";
        options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
    });
    services.AddAuthorization(options =>
    {
        options.AddPolicy("IsSystemAdmin", policy => policy.RequireRole("SystemAdmin"));
        options.FallbackPolicy = options.GetPolicy("IsSystemAdmin");
    });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

【问题讨论】:

    标签: c# asp.net-core razor authorization


    【解决方案1】:

    因为我为隐私政策添加了一个“静态”页面,所以我无意中删除了该行 @model PrivacyPolicyModel 来自 PrivacyPolicy.cshtml。

    因此,PrivacyPolicy.cshtml.cs 中的页面模型被完全跳过,并且没有应用任何 AuthorizeAllowAnonymous 属性。

    其中一个错误我不敢相信我浪费了这么多时间......希望这对将来的某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-10-16
      • 2012-07-20
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 2011-05-11
      相关资源
      最近更新 更多