来自jQuery的基本身份验证外部rest api

时间:2014-01-05 20:46:10

标签: c# jquery api rest

从我正在尝试构建的单个页面应用程序访问外部api时遇到问题。

我可以使用用户名和密码从Postman登录,然后我获得了一个AuthenticationTicket,我可以用于第二次请求的个人数据。

当我尝试从应用程序登录时,我得到了“No'Access-Control-Allow-Origin'标题出现在请求的资源上。”

我无法使用jsonp,因为它必须发布logindata?!

        $.ajax
        ({
          beforeSend: function (x) {
          x.setRequestHeader('Authorization', 'Basic Username=x&Password=y');
        },
        type: "GET",
        url: "https://test.com/api/login/",
        dataType: 'json',
        async: false,
        success: function () {
            alert('you're in!');
        }

    });

邮递员api的回应:

AuthenticationTicket → x
Cache-Control →no-cache
Content-Length →52
Content-Type →application/json; 
charset=utf-8
Date →Sun, 05 Jan 2014 20:29:36 GMT
Expires →-1
LogoutKey → x
Pragma →no-cache
Server →Microsoft-IIS/7.5
SessionTicket → x
X-AspNet-Version → X-AspNet-Version 4.0.30319
X-Powered-By → X-Powered-By
Specifies the technology (ASP.NET, PHP, JBoss, e.g.) supporting the web application (version details are often in X-Runtime, X-Version, or X-AspNet-Version) ASP.NET

2 个答案:

答案 0 :(得分:0)

尝试使用JSONP的数据类型:

 dataType: 'jsonp',

答案 1 :(得分:0)

当然,C#修复了这笔交易。

        WebRequest req = WebRequest.Create(@"https://url.com/api/login/?param=value&param2=value");
        req.Method = "GET";
        req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("Username:Password"));
        HttpWebResponse resp = req.GetResponse() as HttpWebResponse;