Pass Token by the header to each request AngularJS (Authorization)

0

I have the interface-factory.js file that is my factory

app.factory('interfaceAPI', function ($http) {

var _getInterface = function () {
    return $http.get("/api/interfaceapi/getall");
};

var _postInterface = function (objeto) {
    return $http.post("/api/interfaceapi/post", objeto);
};

var _deleteInterface = function (Id) {
    return $http.delete("/api/interfaceapi/delete/" + Id);
};


return {
    getInterface: _getInterface,
    postInterface: _postInterface,
    deleteInterface: _deleteInterface
};

});

The token is already being generated and being saved from the localStorage, I would like to know how to pass the token on the header of each request.

    
asked by anonymous 16.03.2017 / 14:53

2 answers

0

The solution to the problem is you:

var myToken = JSON.parse(localStorage.getItem('token'));
$http.defaults.headers.common['Authorization'] = myToken.token_type + ' ' + myToken.access_token;

you just put the code above:

var _getInterface = function () {

    return $http.get("/api/interfaceapi/getall");
};

var _postInterface = function (objeto) {
    return $http.post("/api/interfaceapi/post", objeto);
};

var _deleteInterface = function (Id) {
    return $http.delete("/api/interfaceapi/delete/" + Id);
};


return {
    getInterface: _getInterface,
    postInterface: _postInterface,
    deleteInterface: _deleteInterface
};

});

    
16.03.2017 / 18:33
0

To set the authorization header, simply do the following:

$http.defaults.headers.common['Authorization'] = 'Basic ' + token;

If this is the case, just change 'Basic' to 'Bearer' or leave only the token, depending on the authentication method you are using.

EDIT:

The header must be set before the request is sent. For example:

var _getInterface = function () {
    var myToken = JSON.parse(localStorage.getItem('token'));
    $http.defaults.headers.common['Authorization'] = myToken.token_type + myToken.access_token;
    return $http.get("/api/interfaceapi/getall");
};

Assuming that myToken.token_type is the token type and myToken.access_token is the token itself.

    
16.03.2017 / 15:11