如何启用CORS支持和NTLM身份验证

时间:2013-04-28 23:58:11

标签: c# http cors ntlm asp.net-web-api

我有一个自托管的c#consol web API。它为使用AngularJS执行异步http请求的多个Web应用程序提供服务。它需要同时具有CORS支持和NTLM身份验证。

我目前都已启用,但看起来我实现它们的方式会导致它们自行取消。我相信这是由我最初的401服务器响应来解决的。这通常会导致两者之间的身份验证握手,但是在Fiddler中查看它,这个初始的401响应缺少一个Access-Control-Allow-Origin标记,这会导致浏览器放弃握手。我已经使用了一个应用程序并给它们相同的主机名来禁用CORS,并且握手工作正常。我通过用原始的HttpSelfHostConfiguration替换我的自定义NtlmSelfHostConfiguration来禁用NTLM身份验证,并且Access-Control-Allow-Origin标记完美地执行以允许CORS。只有当它们都处于活跃状态时,事情才会起作用。

更新:我在CorsHandle中放置了一个不需要它的请求的断点,只是为了确保网络服务器在使用NtlmSelfHostConfiguration时可以实际调用它,并且它被成功命中。我只是想确保NtlmSelfHostConfiguration中没有任何物理上阻止Corshandle被调用的东西。一切正常,看起来我需要找到一种方法来调用CorsHandle,即使是在身份验证失败的请求上也是如此。

这是我的意思:

的Program.cs:

using System.Web.Http;
using System.Web.Http.Validation.Providers;
using System.Web.Http.SelfHost;
namespace DCMAPI
{
    class Program
    {
        static void Main(string[] args)
        {
            string BaseAddress = "http://localhost:8080/";

            //NtlmSelfHostConfiguration is defined in HttpSelfHostConfiguration.cs  
            //it inherits from HttpSelfHostConfiguration 
            //and enables Ntlm Authentication.

            var config = new NtlmSelfHostConfiguration(BaseAddress);

            config.Routes.MapHttpRoute(
                "API Default",
                "api/{controller}/{id}", 
                new { id = RouteParameter.Optional });

            //CorsHandler is also defined in CorsHandler.cs.  It is what enables CORS

            config.MessageHandlers.Add(new CorsHandler());

            var appXmlType =
            config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault
                (t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);                   

            config.Services.RemoveAll
                (typeof(System.Web.Http.Validation.ModelValidatorProvider),
                v => v is InvalidModelValidatorProvider);

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("running");
                Console.ReadLine();
            }

        }
    }
}

NtlmSelfHostConfiguration.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.SelfHost;
using System.Web.Http.SelfHost.Channels;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace DCMAPI
{
    public class NtlmSelfHostConfiguration : HttpSelfHostConfiguration
    {
        public NtlmSelfHostConfiguration(string baseAddress)
            : base(baseAddress)
        { }

        public NtlmSelfHostConfiguration(Uri baseAddress)
            : base(baseAddress)
        { }

        protected override BindingParameterCollection OnConfigureBinding
            (HttpBinding httpBinding)
        {
            httpBinding.Security.Mode =
                HttpBindingSecurityMode.TransportCredentialOnly;

            httpBinding.Security.Transport.ClientCredentialType =
                HttpClientCredentialType.Ntlm;

            return base.OnConfigureBinding(httpBinding);
        }
    }
}

CorsHandle.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http;
using System.Threading.Tasks;
using System.Threading;
using System.Net;

namespace DCMAPI
{
    public class CorsHandler : DelegatingHandler
    {
        const string Origin = "Origin";
        const string AccessControlRequestMethod = "Access-Control-Request-Method";
        const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
        const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
        const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
        const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

        protected override Task<HttpResponseMessage> SendAsync
            (HttpRequestMessage request, CancellationToken cancellationToken)
        {

            bool isCorsRequest = request.Headers.Contains(Origin);
            bool isPreflightRequest = request.Method == HttpMethod.Options;
            if (isCorsRequest)
            {

                if (isPreflightRequest)
                {
                    HttpResponseMessage response = 
                        new HttpResponseMessage(HttpStatusCode.OK);

                    response.Headers.Add(AccessControlAllowOrigin,
                        request.Headers.GetValues(Origin).First());

                    string accessControlRequestMethod =
                        request.Headers.GetValues(AccessControlRequestMethod)
                        .FirstOrDefault();
                    if (accessControlRequestMethod != null)
                    {
                        response.Headers.Add(
                            AccessControlAllowMethods, accessControlRequestMethod);
                    }

                    string requestedHeaders = string.Join(", ",
                        request.Headers.GetValues(AccessControlRequestHeaders));
                    if (!string.IsNullOrEmpty(requestedHeaders))
                    {
                        response.Headers.Add(AccessControlAllowHeaders,
                            requestedHeaders);
                    }

                    TaskCompletionSource<HttpResponseMessage> tcs = 
                        new TaskCompletionSource<HttpResponseMessage>();
                    tcs.SetResult(response);
                    return tcs.Task;
                }
                else
                {
                    return base.SendAsync(request,
                        cancellationToken).ContinueWith<HttpResponseMessage>(t =>
                    {
                        HttpResponseMessage resp = t.Result;
                        resp.Headers.Add(
                            AccessControlAllowOrigin,
                            request.Headers.GetValues(Origin).First());
                        return resp;
                    });
                }
            }
            else
            {
                return base.SendAsync(request, cancellationToken);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:10)

这可能有点晚了,我不确定它会对你有所帮助,但它可能会帮助其他想要同时启用NTLM和CORS的人。

我使用Web API 2作为后端REST API。而AngularJS用于前端。

首先,由于您正在使用NTLM,因此您的呼叫XMLHttpRequest必须发送凭据。在AngularJs中你喜欢这样:

$http.get(url, { withCredentials: true });

然后,您必须在后端启用CORS(在WebApiConfig.Register()中):

        var enableCorsAttribute = new EnableCorsAttribute("*", "*", "*")
            {
                SupportsCredentials = true
            };
        config.EnableCors(enableCorsAttribute);

SupportsCredentials = true表示我们会在回复中添加Access-Control-Allow-Credentials

通配符意味着我们允许:

  • 任何来源的CORS
  • 所有请求标头
  • 任何HTTP动词(方法)