简体   繁体   中英

Authorization Header appended only once in AJAX CORS request

I'm calling my RESTful API from Javascript in a CORS scenario.

I'm using JQuery to send my POST authenticated request. Here is an example:

function post(settings, addAccessToken) {
        settings.type = 'POST';
        settings.cache = false;
        if (settings.dataType === undefined)
            settings.dataType = 'json';
        if (addAccessToken) {
            settings.xhrFields = { withCredentials: true };
            settings.beforeSend = function (request) {
                request.setRequestHeader('Authorization', 'Bearer <my access token>');
            };
            settings.headers = {
                'Authorization': 'Bearer <my access token>'
            };
        }
        return $.ajax(settings);
    }

On server side, I can see the first call coming with the 'Authorization' Header correctly valued, while all the others don't have such Header.

What am I missing?

Thank you

cghersi

I solved my issue so I want to give the answer to everybody else is in the same situation.

1) The problem was to enable OPTIONS http request from server-side. In fact, there is a first call to the same url but with verb 'OPTIONS' and then a second call to the real url with POST|GET method. If the server doesn't properly answer to the first 'OPTIONS' call, eg specifying the correct Allowed Headers etc., the second call doesn't work.

2) The notation

settings.headers = {
 'Authorization': 'Bearer <my access token>'
};

is not working. The only way to setup an header is:

settings.beforeSend = function (request) {
 request.setRequestHeader('Authorization', 'Bearer <my access token>');
};

Hope this can help other people in the future.

cghersi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM