.NET Core 2.2 / WebApi2 / Auth: InvalidOperationException: не указана схема аутентификации, и не найден DefaultChallengeScheme - PullRequest
0 голосов
/ 22 мая 2019

Я пытаюсь использовать атрибут в действии WebApi2 и вернуть 403 при определенных обстоятельствах.Однако я получаю следующее исключение:

InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found.

403 и сообщение все еще возвращаются в ответе, однако.

Вот мой код:

public class ValidCertificateHandler : AuthorizationHandler<ValidCertificateRequirement>
    {
        public ValidCertificateHandler()
        {
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ValidCertificateRequirement requirement)
        {
            // Put logic here to determine if an HTTP Status OK (200) should be returned instead. Then, use context.Suceed().
            var filterContext = (AuthorizationFilterContext)context.Resource;
            var Response = filterContext.HttpContext.Response;
            var message = Encoding.UTF8.GetBytes("Invalid certificate");
            Response.OnStarting(async () =>
            {
                filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                await Response.Body.WriteAsync(message, 0, message.Length);
            });
            context.Fail();
            return Task.CompletedTask;
        }
}

    [ApiController]
    public class TestAuthController : ControllerBase
    {
        [HttpGet]
        [Route("TestAuth")]
        [Authorize(Policy = "ValidateCertificate")]
        public HttpResponseMessage TestAuth()
        {
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                ReasonPhrase = "TestAuth()"
            };
        }
    }

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddAuthorization(options =>
            {
                options.AddPolicy("ValidateCertificate", policy =>
                {
                    policy.Requirements.Add(new ValidCertificateRequirement());
                });
            });

            services.AddSingleton<IAuthorizationHandler, ValidCertificateHandler>();
            services.AddAuthentication(IISDefaults.AuthenticationScheme);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }

public class ValidCertificateRequirement : IAuthorizationRequirement
    {

    }
...