首页 > 解决方案 > Jquery Ajax 不发送授权标头

问题描述

我尝试使用 Jquery Ajax 进行基本身份验证。我像这样向 ajax 请求添加授权标头。

$.ajax({
    headers: {
        "authorization": "basic 123456",
    },
    crossDomain: true,
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: 'http://example.com/Auth.asmx/Authorization',
    data: null,
    dataType: "jsonp",
    success: function (data, status) {
            console.log("Success");
            console.log(data);
    },
    error: function (xmlRequest) {
        console.log("Error");
        console.log(xmlRequest);
    }
});

然后在 ASP.Net Web 服务中,我尝试获取此标头。

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void Authorization(string callback)
{
   string headers = GetRequestHeaders();
}

public string GetRequestHeaders()
{
    HttpContext ctx = HttpContext.Current;
    if (ctx == null || ctx.Request == null || ctx.Request.Headers == null)
    {
        return string.Empty;
    }
    string headers = string.Empty;
    foreach (string header in ctx.Request.Headers.AllKeys)
    {
        string[] values = ctx.Request.Headers.GetValues(header);
        headers += string.Format("{0}: {1}", header, string.Join(",", values));
    }

    return headers;
}

当我打印到标题时,我看不到授权标题

Cache-Control: no-cache
Connection: keep-alive
Pragma: no-cache
Accept: /
Accept-Encoding: gzip, deflate
Accept-Language: tr-TR,tr;q=0.9,en-US;q=0.8,en ;q=0.7
主机:example.com
引用:http://localhost:9200/test.html
用户代理:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0 .3904.108 Safari/537.36

为什么我看不到授权标头以及如何获取此值?

PS我在客户端使用Jquery 2.2.3

我尝试了一些不同的东西。我在本地创建了 Node JS 服务器,而不是向它发送相同的请求。授权标头仍然无法显示。

我使用应用程序“邮递员”来创建和发送请求。我添加授权标头,然后发送到我的服务器(ASP.Net 和 Node JS)。我在此应用程序的请求中看到了授权标头。

对于 ASP.Net,输出是

缓存控制:无缓存

连接:保持活动

接受:/

接受编码:gzip,放气

授权:基本12345

主机:192.168.1.100

用户代理:PostmanRuntime/7.17.1

邮递员令牌:5911bb3a-ea8a-4f81-8579-7e6aed3ced61

然后我从 Postman 应用程序中获取 Jquery AJAX 输出来创建这个请求。

  var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://192.168.1.107:1800",
  "method": "GET",
  "headers": {
    "Authorization": "Basic 12345",
    "User-Agent": "PostmanRuntime/7.17.1",
    "Accept": "*/*",
    "Cache-Control": "no-cache",
    "Postman-Token": "5911bb3a-ea8a-4f81-8579-7e6aed3ced61,3455808c-4a4f-4108-b819-f061b5a8e37e",
    "Host": "192.168.1.100",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "cache-control": "no-cache"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

我像这样更改了我的 Ajax 设置。

 $.ajax({
        "async": true,
        "crossDomain": true,
        "url": "http://192.168.1.107:1800",
        "method": "GET",
        "headers": {
          "Authorization": "Basic 12345",
          "User-Agent": "PostmanRuntime/7.17.1",
          "Accept": "*/*",
          "Cache-Control": "no-cache",
          "Postman-Token": "5911bb3a-ea8a-4f81-8579-7e6aed3ced61,3455808c-4a4f-4108-b819-f061b5a8e37e",
          "Host": "192.168.1.100",
          "Accept-Encoding": "gzip, deflate",
          "Connection": "keep-alive",
          "cache-control": "no-cache"
        },
        success: function (data, status) {
                console.log("Success");
                console.log(data);
                callback("Authorization OK");
        },
        error: function (xmlRequest) {
            console.log("Error");
            console.log(xmlRequest);
            callback("Authorization Error");
        }
    });

当我向我的服务器发送相同的请求时,我再也看不到授权标头了。

我的请求的标题

"主机":"192.168.1.107:1800",

“连接”:“保持活动状态”,

“pragma”:“无缓存”,“缓存控制”:“无缓存”,

"访问控制请求方法":"GET",

“来源”:“ http://localhost:9200 ”,

"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",

“访问控制请求标头”:“授权,缓存控制,邮递员令牌”,

“接受”:“ / ”,

“推荐人”:“ http://localhost:9200/main.html ”,

“接受编码”:“gzip,放气”,

"接受语言":"tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7"

标签: jqueryasp.netajaxbasic-authentication

解决方案


试试这个兄弟:

JS 代码 (AJAX)

$.ajax({
    crossDomain: true,
    type: "POST",
    beforeSend: function (xhr) {
                    xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
                    xhr.setRequestHeader('Authorization', 'Hello 123456');
                },
    contentType: "application/json; charset=utf-8",
    url: 'http://example.com/Auth.asmx/Authorization',
    data: "{'callback':'test'}",
    dataType: "jsonp",
    success: function (data, status) {
        console.log("Success");
        console.log(data);
    },
    error: function (xmlRequest) {
        console.log("Error");
        console.log(xmlRequest);
    }
});

您可以通过以下方式读取该值:

C# 代码

string auth = HttpContext.Current.Request.Headers["Authorization"];

注意:如果这不起作用,请尝试在您的 IIS 版本中配置跨源请求,您可以Web.config根据版本从 IIS 管理面板或从 IIS 管理面板进行配置:https ://enable-cors.org/server_iis7.html


推荐阅读