FridoxFL
FridoxFL

Reputation: 67

AngularJS is not sending Auth header

im trying to make an interceptor that appends an user token if exists on every request, the token exists but it doesnt send it... After the call is made I look at F12 ( Chrome Dev Tools) the call and the Authorization header is not there...

But if I debug it step by step I can see how in the config.headers.Authorization is there my token... but still not sending it throu the request... May I ask for some help please?

This is my interceptor

$httpProvider.interceptors.push(function($q, $location, $cookies){
    return {
        request: function(config){
            config.headers = config.headers || {};
            let token = $cookies.get('user');
            if (token) {
                config.headers.Authorization = 'Bearer ' + token;
            }
            return config;
        },
        response: function(response){
            return response;
        },
        responseError: function(response){
            if(response.status === 401 || response.status === 403){
                $location.path('/login')
            }
            return $q.reject(response);
        }
    }
  })

CORS config

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Authorization');
    next();
}

Config before it be send

config before it be send

req/res preflight req/res preflight

Upvotes: 1

Views: 686

Answers (1)

lin
lin

Reputation: 18402

Ensure that your OPTIONS request does not need an "auth" and you will be fine. The W3 spec for CORS preflight requests says that user credentials should be excluded.

If HTTP-Status 401 has been returned by an OPTIONS request , a subrequest should not be send by the client. But it seems like there is a bug with some browsers. This browsers does send a subrequest even if the OPTIONS request returned 401.

In node.js you could check the request method by using req.method === 'OPTIONS'.

Upvotes: 2

Related Questions