在IIS CORS请求与Windows验证401响应启动在IIS CORS请求与Windows验证4

2019-05-14 11:17发布

我试图让我的WebAPI项目CORS支持,如果我启用匿名身份验证,然后一切工作正常,但与Windows验证+禁用匿名身份验证,OPTIONS请求发送总是返回401未经授权的响应。 要求它是该域的网站,所以应该能够拨打电话,有没有什么办法来解决问题,而无需禁用Windows身份验证?

Answer 1:

您可以允许匿名用户唯一的选择动词。

<system.web>
  <authentication mode="Windows" />
    <authorization>
      <allow verbs="OPTIONS" users="*"/>
      <deny users="?" />
  </authorization>
</system.web>

根据W3C规范,浏览器从排除预检CORS的用户凭据: https://dvcs.w3.org/hg/cors/raw-file/tip/Overview.html#preflight-request



Answer 2:

事隔多年,但通过从@dariusriggins和@法立的答案,我已经成功地将下面的代码添加到我的Global.asax:

    public void Application_BeginRequest(object sender, EventArgs e)
    {
        string httpOrigin = Request.Params["HTTP_ORIGIN"];
        if (httpOrigin == null) httpOrigin = "*";
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", httpOrigin);
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Token");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");

        if (Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.StatusCode = 200;
            var httpApplication = sender as HttpApplication;
            httpApplication.CompleteRequest();
        }
    }

该httpOrigin实际上是在允许的主机列表中抬起头来,但只是复杂的事情。 这意味着,所有其他请求被验证,但选择刚刚返回。

谢谢你这个问题,我会一直没有失去它!



Answer 3:

From MS:

If you disable anonymous authentication, it’s by design that IIS would return a 401 to any request. If they have enabled Windows auth, the 401 response in that case would have a WWW-Authenticate header to allow the client to start an authentication handshake. The question then becomes whether the client that the customer is using can do Windows authentication or not.

Finally, it seems like there might be an underlying question about whether it’s possible or not to configure a URL such that anonymous access is allowed for one verb (OPTIONS, in this case), but require Windows authentication for other verbs. IIS does not support this through simple configuration. It might be possible to get this behavior by enabling both Anonymous and Windows authentication, setting ACLs on the content that deny access to the anonymous user, and then configuring the handler mapping for the URL in question so that it does not verify the existence of the file associated with the URL. But it would take some playing with it to confirm this.



Answer 4:

解决这个问题的最简单的方法是创建条件REQUEST_METHOD = ^ $ OPTIONS重写规则。 然后设置动作要自定义的响应,其设置为200 OK。 然后,所有的选项请求将用200代替401回应此事将解决CORS问题。

当然,你还需要确保你有正确的跨起源请求头。

启用了集成身份验证时,系统将停止选项请求(其中不具有任何凭据)与401响应。



Answer 5:

接受的答案是正确的,但是我是用故障排除设置一个“与iisnode和NPM CORS模块节点”一会儿一个REST API和不舒服只有启用匿名身份验证的所有用户。 由于它的一个节点应用System.Web程序标签并没有做太多。 我结束了以下除了web.config中:

<system.webServer>
<security>
  <requestFiltering>
    <hiddenSegments>
      <add segment="node_modules" />
    </hiddenSegments>
  </requestFiltering>
  <authorization>
    <add accessType="Allow" verbs="OPTIONS" users="?" />
    <add accessType="Deny" verbs="GET, PUT, POST, DELETE" users="?" />
  </authorization>
</security>
</system.webServer>


Answer 6:

我今天碰上同样的问题,由于错误的IE 10和11 ,我使用ServiceStack代替的WebAPI,但是这种方法可以为你正常工作。

  1. 启用Windows集成和匿名身份验证在IIS网站。
  2. 对ServiceStack管道一系列的过滤器,
    • 为了处理一个Cors和OPTIONS请求,在选项的要求,我想补充必要的头和结束的要求,
    • 过滤器检查includng的HttpRequest被验证?
    • 等过滤器,

通过所有过滤器后,它执行的服务。

CorsFeature.cs

AuthenticateFilter

在我的APPHOST,

appHost.Plugins.Add(new CorsFeature());

appHost.RequestFilters.Add(AuthenticateFilter.Authenticate);

我已经修改了CorsFeature处理除了OptionsRequest对添加标题,验证器检查认证的请求!



Answer 7:

相关问题:IIS劫持CORS预检OPTIONS请求

合并来自多个地方发现的答案信息。 如果您需要启用一个ASP.net页方法使用Windows身份验证在Intranet CORS,这是什么似乎工作。 如果没有改变web.config ,这是行不通的。

您需要添加这Global.asax

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        string httpOrigin = HttpContext.Current.Request.Params["HTTP_ORIGIN"] ?? HttpContext.Current.Request.Params["ORIGIN"] ?? "*";
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", httpOrigin);
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Token");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.StatusCode = 200;
            var httpApplication = sender as HttpApplication;
            httpApplication.CompleteRequest();
        }
    }

而这web.config

 <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." 
           verb="*" type="System.Web.Handlers.TransferRequestHandler" 
           preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>


Answer 8:

我使用的Web API和OWIN,我想尽提出解决方案,但只有工作的事情是以下

//use it in your startup class
app.Use((context, next) =>
{
    if (context.Request.Headers.Any(k => k.Key.Contains("Origin")) && context.Request.Method == "OPTIONS")
    {
        context.Response.StatusCode = 200;
        context.Response.Headers.Add("Access-Control-Allow-Origin", new string[1] { "ALLOWED_ORIGIN" });
        context.Response.Headers.Add("Access-Control-Allow-Headers", new string[4] { "Origin", "X-Requested-With", "Content-Type", "Accept" });
        context.Response.Headers.Add("Access-Control-Allow-Methods", new string[5] { "GET", "POST", "PUT", "DELETE", "OPTIONS" });
        context.Response.Headers.Add("Access-Control-Allow-Credentials", new string[1] { "true" });

        return context.Response.WriteAsync("");
    }

    return next.Invoke();
});

//this is important! Without it, it didn't work (probably because the middleware was too late)
app.UseStageMarker(PipelineStage.Authenticate);

您需要在您的OWIN启动类的一个地方插入此代码。 它调用的重要app.UseStageMarker(PipelineStage.Authenticate)否则操作前检查失败。 为进一步UseStageMarker的相关信息- > https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline

同样重要的是,你需要明确地定义允许的头。 如果你使用它会失败*作为占位符。

也许它可以帮助别人。



Answer 9:

我明白这是几个可能的解决方案一个老问题(以及更多的问题),但如果任何人遇到这样,IIS 1.0 CORS可作为'17十一月的:

https://blogs.iis.net/iisteam/introducing-iis-cors-1-0

https://docs.microsoft.com/en-us/iis/extensions/cors-module/cors-module-configuration-reference

您可以通过IIS的Windows平台安装程序(WPI)下载。 这应该解决您的许多CORS身份验证问题。 请享用!



Answer 10:

什么(用AngularJS或JQuery的工作时)工作对我来说是withCredentials补充:真在客户端的每个请求:

$http.get("http://localhost:88/api/tests", {withCredentials :true})

和启用服务器上CORS,这是从的NuGet Microsoft.Owin.Cors完成,如下面将它启动:

public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        ConfigureOAuth(app);

        WebApiConfig.Register(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(config);

    }

参考文献:

  • 在服务器CORS(参见第11步): http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
  • CORS在客户端: http://brockallen.com/2012/12/15/cors-and-windows-authentication/


Answer 11:

在EnableCorsAttribute启用SupportCredentials在WebApiConfig.cs为我做的伎俩:

public static void Register(HttpConfiguration config)
{        
    //enable cors request just from localhost:15136 
    var cors = new EnableCorsAttribute("http://localhost:15136", "*", "*");
    cors.SupportsCredentials = true;
    config.EnableCors(cors);

    //other stuff
}

https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

确保你从JavaScript调用时发送证书( {withCredentials :true}



文章来源: 401 response for CORS request in IIS with Windows Auth enabled