【问题标题】:.Net Core WebAPI CORS with Windows Authentication.Net Core WebAPI CORS 与 Windows 身份验证
【发布时间】:2018-01-07 04:43:42
【问题描述】:

我有一个 .Net Core WebAPI 服务,我为它启用了 CORS(使用下面的代码),在项目的属性中我禁用了匿名身份验证并启用了 Windows 身份验证。 POST 和 PUT 端点在启用匿名身份验证的情况下工作,但在禁用时会失败。我明白了

OPTIONS http://localhost:64113/api/ 401 (Unauthorized)

启用 CORS 的代码

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

角度代码

    public XXX(data: any): Observable<Response> {
    return this.http.put(this.baseUrl, data,
        { withCredentials: true });
}

有人有这方面的经验吗?

谢谢

【问题讨论】:

    标签: angular asp.net-web-api asp.net-core-webapi


    【解决方案1】:

    对于使用 .NET Core 3.1 及更高版本的用户,这里有一个完整的解决方案(前端到后端):

    我的问题:当我在我的 Web API 上启用 Windows 身份验证时,我无法从我的 react 应用程序获取调用到我的 .NET Core 3.1 Web API,CORS 吓坏了。使用匿名身份验证它可以工作,但在启用 Windows 身份验证时不能。

    1.launchSettings.json

    这将仅用于您的开发环境,请确保您的产品服务器上的 IIS 中也启用了 Windows 身份验证。

    {
      "iisSettings": {
        "windowsAuthentication": true,
        "anonymousAuthentication": false,
        "iisExpress": {
          "applicationUrl": "http://localhost:58747",
          "sslPort": 0
        }
      },
     {... more settings if any}
    }
    

    2.Startup.cs:

    CORS 政策在此处启用。方法的顺序在这里很重要。此外,您不需要在 web.config 中设置这些

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy", //give it the name you want
                           builder =>
                           {
                               builder.WithOrigins( "http://localhost:3000", //dev site
                                                    "production web site"
                                                   .AllowAnyHeader()
                                                   .AllowAnyMethod()
                                                   .AllowCredentials();
                           });
        });
    
        //database services here
    
        services.AddControllers();
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.UseRouting();
    
        // global policy same name as in the ConfigureServices()
        app.UseCors("CorsPolicy");
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
    

    3.控制器:

    using Microsoft.AspNetCore.Cors;
    ... your other usings
    
    namespace ProjectTest.Controllers
    {
        [ApiController]
        [EnableCors("CorsPolicy")] //THIS HERE needs to be the same name as set in your startup.cs
        [Route("[controller]")]
        public class FooController:Controller
        {
            [HttpGet("getTest")]
            public JsonResult GetTest()
            {
                return Json("bar");
            }
        }
    }
    

    4.React Component fetch 调用示例:

    “凭据:'include'”是秘密

        await fetch('http://localhost:3000/Foo/getTest', {
            method: 'GET',
            credentials: 'include'
        }).then(resp => resp.json());
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题。终于得到了对我有用的解决方案。所以你可以尝试遵循这个模式:

      1. 通过执行以下操作启用 CORS 中间件(您已经完成):

        services.AddCors(options ={
          ...
          //describe your options here
          ...    
        });
        
      2. 为 IIS/IIS Express 启用 Windows 身份验证和匿名身份验证(取决于您使用什么)。

      3. 使用 forwardWindowsAuthToken="true" 标志将 web.config 添加到项目的根文件夹。在我的示例中,它看起来像这样:

        <?xml version="1.0" encoding="utf-8"?>
        <configuration>
          <system.webServer>
           <handlers>
             <remove name="aspNetCore"/>
             <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
           </handlers>
           <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true"/>
          </system.webServer>
        </configuration>  
        
      4. [Authorize] 属性应用于您的控制器/操作。就是这样。现在,您只需访问 User.Identity.Name 属性即可发送 POST 和 PUT 请求以及获取用户身份

      【讨论】:

        猜你喜欢
        • 2019-08-26
        • 1970-01-01
        • 2020-03-04
        • 2012-09-12
        • 2020-06-05
        • 2018-08-03
        • 1970-01-01
        • 2019-11-28
        • 2021-04-20
        相关资源
        最近更新 更多