Asp.Net Core 2.1授权策略未触发处理程序

时间:2019-10-22 17:02:40

标签: authorization asp.net-core-2.1

我有一个非常简单的.net core 2.1网站(使用Windows Auth),当我对需求和处理程序使用单独的类时,控制器上的策略无法触发处理程序,但是如果合并这两个类,则可以使用。查看示例,这应该很简单,但是由于某种原因,它将无法正常工作。

任何建议,我的代码如下所示

需求和处理程序

using Microsoft.AspNetCore.Authorization;
using System.Threading.Tasks;
namespace WebApplication4
{
    public class TestRequirement : IAuthorizationRequirement
    {
        public TestRequirement(){ }
    }
    // Break point in Handler never hit
    public class TestHandler : AuthorizationHandler<TestRequirement>
    {

        public TestHandler(){}
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TestRequirement requirement)
        {
            context.Succeed(requirement);
            return Task.CompletedTask;
        }
    }
    // Merged Requirement & Handler works
    public class RequirementPlusHandler : IAuthorizationHandler, IAuthorizationRequirement
    {
        public RequirementPlusHandler(){ }
        public Task HandleAsync(AuthorizationHandlerContext context)
        {
            context.Succeed(this);
            return Task.CompletedTask;
        }
    }
}

启动

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace WebApplication4
{
    public class Startup
    {
        public Startup(IConfiguration configuration){Configuration = configuration;}
        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(Microsoft.AspNetCore.Server.IISIntegration.IISDefaults.AuthenticationScheme); // Causes a 403 page to show if no access
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Test", policy =>
                {
                    policy.AddRequirements(new TestRequirement()); // Not work
                    //policy.AddRequirements(new RequirementPlusHandler()); // Works
                });
            }); 
         }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication(); // Just added but not fix
            app.UseDeveloperExceptionPage();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();


            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

0 个答案:

没有答案