2

我已经设置了一个 web api 以允许使用基本身份验证进行跨域访问。当我向 API 发出跨域 GET 请求时,它工作正常,并且我在自定义消息处理程序的“授权”标头中获取令牌。但是在发起跨域 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;
            }                
        }
    }

提前致谢!

4

2 回答 2

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;
        }
于 2013-10-18T08:55:06.090 回答
0

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

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

于 2013-09-25T16:52:56.870 回答