Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorization Header is null when making jQuery Ajax request

I have went through pretty much all of the articles I can find and followed what was suggested and somehow when processing the request on server side the Authorization header is null.

The back-end is a ASP.Net MVC Web API and I've implemented a filter to do the authentication. I've tried this using Postman and setup the Authorization header and I have verified that the back-end code works.

However, I can't seem to make it work via an ajax call in jQuery.

Here is the jQuery Ajax request:

//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);
        }
    });

And below is the snippet of code that processes the request...

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);
    }

When I inspect the actionContext.Request.Header, I can see Authorization but its value is null.

What am I doing wrong here? Thanks in advance.

EDIT: I am also including some settings in the web.config file which might help figure out what's causing the problem.

<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: Below is the Raw Http Request

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: It seems that it has something to do with doing a Cross Origin Request. When I comment out the dataType: "jsonp" attribute on the ajax call, I can now see that the Authorization header is being set. Now the problem is, how do I set the header when expecting a jsonp result or doing CORS?

like image 361
Jaime Avatar asked Oct 20 '22 06:10

Jaime


1 Answers

To solve this problem you need to do like this

  1. remove all custom headers from your web.config
  2. Add this reference in your web api project:

    System.Web.Http.Cors

  3. add the following line code inside the Register method of the WebApiConfig class.

    config.EnableCors();

  4. Add the following attribute in your controller(s)

    [EnableCors(origins: "", headers: "", methods: "*", SupportsCredentials = true)]

like image 97
natnael88 Avatar answered Oct 23 '22 02:10

natnael88