且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Windows身份验证的ASP.NET Core Web API-Cors请求未经授权

更新时间:2023-02-17 13:38:05

您可能需要阅读以下主题: https://github.com/aspnet/CORS/issues/60 。您可以混合使用匿名和NTLM,以便不会拒绝您的CORS预检(因为它们不包含Windows凭据)。 IIS在进入中间件之前就已经处理过NTLM身份验证,因此这很可能是IIS。您可能需要允许匿名COR进行飞行前检查。


In my asp.net core web api, I've configured Cors as per the article from MS documentation. The web api app is using windows authentication (Anonymous Authentication is Not enabled). Cor's policy is created and middle ware is added as below in the startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.WithOrigins("http://localhost:4200")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
            );
    });

    services.AddMvc().AddJsonOptions(options => {
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{         
    //Enable CORS policy 
    app.UseCors("CorsPolicy");
    app.UseMvc();
}

Also applied the policy per controller level

[EnableCors("CorsPolicy"), Route("api/[controller]")]
public class LocationController : BaseController<Location>
{
  //code
}

Options request is getting Unauthorized. The request & response looks like

I have seen similar questions and tried almost every solution but the options request is still failing.

You may want to read this thread: https://github.com/aspnet/CORS/issues/60. You can mix anonymous and NTLM so that your CORS preflights aren't denied (since they don't include windows credentials). IIS handles NTLM authentication before it even gets to the middleware so this is probably an IIS thing. You may need to allow anonymous CORs preflight checks.