AspNetCore 拒绝预检消息

AspNetCore rejects preflight messages

我们有一个 HttpSys 侦听器,它应该接受作为 NTLM、协商或 JWT 的身份验证。

问题是 HttpSys 似乎拒绝了预检消息和带有 Bearer 令牌 (JWT) 的消息

我们的监听器是这样构建的

        _host = new WebHostBuilder()
            .UseHttpSys(options =>
            {
                options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
                options.Authentication.AllowAnonymous = false;
            })
            .UseUrls($"http://+:{PortNo}/")
            .UseUnityServiceProvider(IocContainer)
            .ConfigureServices(services => { services.AddSingleton(_startUpConfig); })
            .UseStartup<StartUp>()
            .Build();

我们为服务添加 CORS 和身份验证:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(o => o.AddPolicy("AllowAll", builder =>
        {
            builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials().WithOrigins("*");
        }));

        services.AddAuthentication(o =>
        {
            o.DefaultAuthenticateScheme = HttpSysDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
            .AddJwtBearer(o =>
            {
                o.Events = new JwtBearerEvents { OnTokenValidated = context => AuthMiddleWare.VerifyJwt(context, _jwtPublicKey) };
            });

我们 运行 在 Chrome 申请了 angular 申请,该申请被拒绝并显示以下错误消息 "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. "

此外,任何 Bearer 令牌消息都会被拒绝。调试显示我们用于验证 JWT 承载的代码从未到达 (AuthMiddleWare.VerifyJwt)

我的猜测是 HttpSys 拒绝任何未携带 Ntlm 或协商令牌的消息。只是我不知道如何解决这个问题

在 .net Framework 中,我们使用 AuthenticationSchemeSelectorDelegate 来 运行 以下代码,它允许 OPTIONS 消息和带有 Bearer 令牌的消息通过 HttpSys 侦听器

    public AuthenticationSchemes EvaluateAuthentication(HttpListenerRequest request)
    {
        if (request.HttpMethod == "OPTIONS")
        {
            return AuthenticationSchemes.Anonymous;
        }

        if (request.Headers["Authorization"] != null && request.Headers["Authorization"].Contains("Bearer "))
        {
            return AuthenticationSchemes.Anonymous;
        }

        return AuthenticationSchemes.IntegratedWindowsAuthentication;
    }

我们现在可以正常工作了。基本上,问题是允许所有三种身份验证方法在 Asp Net Core 中不受支持。

所以诀窍是在管道中实现我们自己的身份验证。

另请参阅此 github 问题: https://github.com/aspnet/AspNetCore/issues/13135