Web API的跨域身份验证



我知道这是一个古老的问题,我已经阅读了许多有关它的文章,最后到达了这里。每件事都没有身份验证(没有[System.Web.Mvc.authorize]):

  1. API控制器:

    using System.Web.Http;
    using System.Web.Mvc;
    namespace WebApi.Controllers
    {
        [System.Web.Mvc.Authorize]
        public class ProductsController : ApiController
        {
            public IEnumerable<string> GetAllNames()
            {
                return new List<string> {"abc", "def", User.Identity.Name};
            }
            public string GetName(string name)
            {
                return name;
            }
        }
    }
    
  2. web.config添加了下面的四行以支持COR。

      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <modules>
          <remove name="WebDAVModule"/><!-- ADD THIS to enable POST/DELETE -->
        </modules>
        <handlers>
          <remove name="WebDAV" /><!-- ADD THIS to enable POST/DELETE -->
          <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
          <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
          <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
          <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFrameworkv4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
          <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFramework64v4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
          <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>
        <httpProtocol>
          <customHeaders>
            <clear />
            <!-- Adding the following custom HttpHeaders will help prevent CORS from stopping the Request-->
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
          </customHeaders>
        </httpProtocol>
      </system.webServer>
    

但是,当[授权]添加到API控制器中时,一切都会出错。

这是页面调用API,我从网络上读取的最多7个解决方案将是一本教科书,如果其中任何一个都可以使用。许多人说"它对我有用",但对我无济于事。

我评论了标题下的所有解决方案,并记录了它引起的错误。

        var host = 'http://localhost:54364/api/products/';
        userName = "name@domain.com";
        password = "password";
        $(document).ready(function () {
            //Solution 1: OPTIONS http://localhost:54364/api/products/GetAllNames?name=someone 405 (Method Not Allowed) / http://localhost:54364/api/products/GetAllNames?name=someone. Invalid HTTP status code 405  
            //$.ajaxSetup({
            //    headers: {
            //        'Authorization': "Basic " + btoa("cheny@cheny.com" + ":" + "nodenode")
            //    }
            //});
            $.ajax({
                type: "GET",
                url: host + "GetAllNames",
                dataType: 'json',
                //Solution 2: Ok, but User.Identity.UserName returns "", an empty string; I think it does not work at all.
                //username: userName,
                //password: password,
                async: false,
                //Solution 3: GET http://localhost:54364/api/products/GetAllNames?name=someone 405 (Method Not Allowed) / OPTIONS http://localhost:54364/api/products/GetAllNames?name=someone 405 (Method Not Allowed) / XMLHttpRequest cannot load http://localhost:54364/api/products/GetAllNames?name=someone. Invalid HTTP status code 405
                //headers: { "Authorization": btoa("Basic " + userName + ":" + password) },
                //Solution 4: XMLHttpRequest cannot load http://localhost:54364/api/products/GetAllNames. Wildcards cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:64710' is therefore not allowed access.
                //xhrFields: {
                //    withCredentials: true
                //},
                beforeSend: function (xhr) {
                    //Solution 5: Same with solution 2.
                    //xhr.withCredentials = true;
                    //Solution 6: OPTIONS http://localhost:54364/api/products/GetAllNames?name=someone 405 (Method Not Allowed) / OPTIONS http://localhost:54364/api/products/GetAllNames?name=someone 405 (Method Not Allowed)  / XMLHttpRequest cannot load http://localhost:54364/api/products/GetAllNames?name=someone. Invalid HTTP status code 405 
                    //xhr.setRequestHeader("Authorization", "Basic " + btoa(userName + ":" + password));
                    //Solution 7 ( 5 + 6 ): same with solution 6.
                },
                crossDomain: true,
                success:
                    function(data) {
                        // On success, 'data' contains a list of products.
                        $.each(data, function(key, item) {
                            // Add a list item for the product.
                            $('<li>', { text: formatItem(item) }).appendTo($('#ajax'));
                        });
                    }
            });

使用Ajax和Web API(仅仅2天的经验),我想我可能会错过一些东西,例如,解决方案4没有用户名/密码信息,它如何工作?

提前感谢,欢迎任何评论。

问题在您的响应的Access-Control-Allow-Origin标题中。如果您使用的是身份验证,则不能使用通配符*。您需要明确设置域。

如果要使用withCredentials: true,则您的服务器必须将额外的标头Access-Control-Allow-Credentials设置为true

Access-Control-Allow-Credentials: true

相关内容

  • 没有找到相关文章

最新更新