Web Api跨域基本身份验证

时间:2013-06-10 20:13:20

标签: cross-domain cors basic-authentication asp.net-web-api

我已经设置了一个web api,允许使用基本身份验证进行跨域访问。当我向API发出跨域GET请求时,它工作正常,我在自定义消息处理程序的“Authorization”标头中获取令牌。但是当启动跨域POST请求时,我没有获得“授权”标头,这就是无法验证请求的原因。

任何帮助都将受到高度赞赏。

以下是我的跨域访问自定义消息处理程序的代码。

    using System;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;

    namespace MyWebApi.Handlers
    {
        public class XHttpMethodOverrideDelegatingHandler : DelegatingHandler
        {
            static readonly string[] HttpOverrideMethods = { "PUT", "DELETE" };
            static readonly string[] AccessControlAllowMethods = { "POST", "PUT", "DELETE" };
            private const string HttpMethodOverrideHeader = "X-HTTP-Method-Override";
            private const string OriginHeader = "ORIGIN";
            private const string AccessControlAllowOriginHeader = "Access-Control-Allow-Origin";
            private const string AccessControlAllowMethodsHeader = "Access-Control-Allow-Methods";
            private const string AccessControlAllowHeadersHeader = "Access-Control-Allow-Headers";

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


                 var authHeader = request.Headers.Authorization;

                if (authHeader == null || authHeader.Scheme != "Basic" || string.IsNullOrWhiteSpace(authHeader.Parameter))
                {
                    return CreateUnauthorizedResponse();
                }

                if (request.Method == HttpMethod.Post && request.Headers.Contains(HttpMethodOverrideHeader))
                {
                    var httpMethod = request.Headers.GetValues(HttpMethodOverrideHeader).FirstOrDefault();
                    if (HttpOverrideMethods.Contains(httpMethod, StringComparer.InvariantCultureIgnoreCase))
                        request.Method = new HttpMethod(httpMethod);
                }

                var httpResponseMessage = base.SendAsync(request, cancellationToken);

                if (request.Method == HttpMethod.Options && request.Headers.Contains(OriginHeader))
                {
                    httpResponseMessage.Result.Headers.Add(AccessControlAllowOriginHeader, request.Headers.GetValues(OriginHeader).FirstOrDefault());
                    httpResponseMessage.Result.Headers.Add(AccessControlAllowMethodsHeader, String.Join(", ", AccessControlAllowMethods));
                    httpResponseMessage.Result.Headers.Add(AccessControlAllowHeadersHeader, HttpMethodOverrideHeader);
                    httpResponseMessage.Result.StatusCode = HttpStatusCode.OK;
                }
                //No mater what the HttpMethod (POST, PUT, DELETE), if a Origin Header exists, we need to take care of it
                else if (request.Headers.Contains(OriginHeader))
                {
                    httpResponseMessage.Result.Headers.Add(AccessControlAllowOriginHeader, request.Headers.GetValues(OriginHeader).FirstOrDefault());
                }

                return httpResponseMessage;
            }

            private Task<HttpResponseMessage> CreateUnauthorizedResponse()
            {
                var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                response.Headers.Add("WWW-Authenticate", "Basic");

                var taskCompletionSource = new TaskCompletionSource<HttpResponseMessage>();
                taskCompletionSource.SetResult(response);
                return taskCompletionSource.Task;
            }
        }
    }

我在Application_Start中注册了上述处理程序,如下所示:

    namespace MyWebApi
    {
        public class Global : System.Web.HttpApplication
        {
            protected void Application_Start(object sender, EventArgs e)
            {
                RouteTable.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new {id = RouteParameter.Optional});
                GlobalConfiguration.Configuration.MessageHandlers.Add(new XHttpMethodOverrideDelegatingHandler()); 
                GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());
            }
        }
    }

在不同域项目的客户端,我正在尝试使用以下代码添加新记录。

     AddUser {

                var jsonData = {
                    "FirstName":"My First Name",
                    "LastName": "My Last Name",
                    "Email": "my.name@mydomain.com",
                    "Password": "MyPa$$word"
                };

                $.ajax({
                    type: "POST",
                    dataType: 'json',
                    url: "http://localhost:4655/api/user/signup",
                    beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic xxxxxxxxxxxxxx"); },
                    accept: "application/json",
                    data: JSON.stringify(jsonData),
                    success: function (data) {
                        alert("success");
                    },
                    failure: function (errorMsg) {
                        alert(errorMsg);

                    },
                    error: function (onErrorMsg) {
                        alert(onErrorMsg.statusText);
                    },
                    statusCode: function (test) {
                        alert("status");
                    }
                });
            });

以下是我的用户控制器的代码。

    namespace MyWebApi.Controllers
    {
        public class UserController : ApiController
        {

            [HttpPost]
            [ActionName("Adduser")]
            public int Post(UserModel source)
            {
                    if (source == null)
                    {
                        throw new ArgumentNullException("source");
                    }
                    Db.Users.Add(source);
                    Db.SaveChanges();

                    return source.UserId;
            }                
        }
    }

提前致谢!

2 个答案:

答案 0 :(得分:0)

我发现如果我在我的跨域(POST)XHR请求中包含基本身份验证凭据,浏览器(IE,Chrome,Firefox)会在请求到达我的服务器之前拒绝该请求 - 这甚至都是如此如果我在我的初始$ .ajax()请求中指定withCredentials:true。我猜这可能是CORS规范中需要的东西。但我认为简短的回答是您无法在CORS请求中指定基本身份验证。

当然,您可以通过其他方式解决这个问题,方法是将用户ID和密码作为URL的一部分传递,因此我并不完全清楚他们认为通过限制它们会获得什么,但可能他们有一些原因。

答案 1 :(得分:0)

您需要使用[HttpOptions]和[HttpPost]来装饰您的控制器。否则当它使用OPTIONS动词发出请求时,它将抛出404.所以你的控制器将是

        [HttpPost]
        [HttpOptions]
        [ActionName("Adduser")]
        public int Post(UserModel source)
        {
                if (source == null)
                {
                    throw new ArgumentNullException("source");
                }
                Db.Users.Add(source);
                Db.SaveChanges();

                return source.UserId;
        }