发出jQuery Ajax请求时,授权头为空

Authorization Header is null when making jQuery Ajax request

本文关键字:授权 jQuery Ajax 请求 发出      更新时间:2023-09-26

我已经阅读了我能找到的几乎所有文章,并遵循了建议,但不知何故,在服务器端处理请求时,授权头是空的。

后端是ASP。Net MVC Web API,我已经实现了一个过滤器来进行身份验证。我已经尝试使用Postman并设置了Authorization头,并且我已经验证了后端代码可以工作。

然而,我似乎不能通过jQuery中的ajax调用使其工作。

这是jQuery Ajax请求:

//do an ajax call to the api
    $.ajax({
        url: "http://localhost:55602/api/EvaluateTableExpression?callback=?",
        type: "GET",
        data: "json=" + escape(JSON.stringify({
            "fdml": "HR.Employee as emp { emp.ID, emp.FIRSTNAME, emp.PRSNAME }"
        })),
        dataType: "jsonp",
        beforeSend: function(request) {
            request.setRequestHeader("Authorization", "Basic " + btoa("master:servant"));
        },
        success: function(data, status) {
            console.log(data);
            if (!data.ErrorsOccurred) {
                var header = data.Value.Header.Columns;
                var records = processRecords(header, data.Value.Rows.Rows);
                renderGrid(header, records, $("#employeeGrid"));
            }
        },
        error: function(xhr, textStatus, errorThrown){
            console.log(errorThrown);
        }
    });

下面是处理请求的代码片段…

public override void OnAuthorization(HttpActionContext actionContext)
    {
        // in case the user is authorized using forms authentication
        // check the header for basic authentication
        if (Thread.CurrentPrincipal.Identity.IsAuthenticated) return;
        var authHeader = actionContext.Request.Headers.Authorization;
        if (authHeader != null)
        {
            if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) &&
                !String.IsNullOrWhiteSpace(authHeader.Parameter))
                if (AuthenticateUser(authHeader)) return;
        }
        HandleUnauthorizedRequest(actionContext);
    }

当我检查actionContext.Request。头,我可以看到授权,但它的值是空的。

我在这里做错了什么?提前谢谢。

EDIT:我也包括一些设置在web中。配置文件,这可能有助于找出导致问题的原因。

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Request-Headers" value="Authorization, Content-Type"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type, Authorization" />
    <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" />
  </customHeaders>
</httpProtocol>
<authentication mode="Forms" />

EDIT:以下是原始Http请求

GET /api/EvaluateTableExpression?callback=jQuery21109280835636891425_1403905133542&j‌​son=%7B%22fdml%22%3A%22HR.Employee%20as%20emp%20%7B%20emp.ID%2C%20emp.FIRSTNAME%2‌​C%20emp.PRSNAME%20%7D%22%7D&_=1403905133544 
HTTP/1.1 Host: localhost:55602 
Connection: keep-alive 
Accept: / User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
Referer: localhost/FDMWeb Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8

EDIT:这似乎与做跨原产地请求有关。当我注释掉ajax调用上的dataType:"jsonp"属性时,现在可以看到正在设置授权标头。现在的问题是,当期望json结果或做CORS时,我如何设置标题?

要解决这个问题,你需要这样做

  1. 从web.config中删除所有自定义头在你的web api项目中添加这个引用:

    System.Web.Http.Cors

  2. WebApiConfig类的Register方法中添加以下行代码。

    config.EnableCors ();

  3. 在控制器中添加以下属性

    [EnableCors起源:"",标题:"",方法:"*",supportscredals = true)]