【问题标题】:Web API 2 AuthenticationWeb API 2 身份验证
【发布时间】:2014-01-28 16:32:26
【问题描述】:

我正在尝试对我的移动应用程序(用于从 Visual Studio 运行的测试)进行身份验证,以在单页应用程序中验证我的 Web API 2 身份验证令牌

但 Ajax 总是取消状态为取消

我已启用 CORS,如下所示

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

//Use only bearer token authentication
            config.SuppressDefaultHostAuthentication();

网络配置

 <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <roleManager enabled="true" />
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
    </httpModules>
  </system.web>

我的 Ajax 请求

 $.ajax('http://retail.leap-tel.com/token', {
                type: "POST",
                data: data,
                xhrFields: {
                    withCredentials: true
                }

Chorme 开发者工具日志

状态:已取消

Request URL:http://retail.leap-tel.com/token
Request Headersview source
Accept:*/*
Cache-Control:no-cache
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Origin:http://localhost:1539
Pragma:no-cache
Referer:http://localhost:1539/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Form Dataview sourceview URL encoded

【问题讨论】:

    标签: c# jquery asp.net ajax asp.net-web-api


    【解决方案1】:

    我在 DurandalAuth 中进行了一些更改以启用 CORS,并在另一个 repo 中创建了一个示例 Javascript 客户端

    看看

    https://github.com/yagopv/DurandalAuth/commit/4e7c09bc589345c946319b42d320e2b4d8313573

    https://github.com/yagopv/DurandalAuthjsclient

    也许您的主要问题是关于使用默认的 Web API CORS 属性。您应该改用 Microsoft.Owin.Cors 属性来使用 Owin 中间件

    【讨论】:

      【解决方案2】:
      public static void Register(HttpConfiguration config)
      {
          var corsAttribute = new EnableCorsAttribute("*", "*", "*");
          config.EnableCors(corsAttribute);
      
          // Web API configuration and services
          // Web API routes
          config.MapHttpAttributeRoutes();
      }
      

      webapiConfig类注册方法中添加cors属性为应用程序级别。

      【讨论】:

      • 部分代码在灰色框中。请改进它以获得更好的可读性
      猜你喜欢
      • 1970-01-01
      • 2017-07-27
      • 2017-03-04
      • 2016-04-05
      • 1970-01-01
      • 2017-10-22
      • 2012-06-16
      • 2016-07-03
      • 1970-01-01
      相关资源
      最近更新 更多