Pass Token by header to each request AngularJS

3

I'm implementing tokens on a system, I already have token generated and saved the same in sessionStorage . How can I create a service or interceptor to put this token in Header of each request?

I currently do the services that are responsible for the request as follows:

angular.module("Security").factory("usuarioAPI", function ($http, config) {


  var _autenticar = function(usuario){
    return $http.post(config.baseURL + '/SecurityVraptor/usuario/', usuario);
  };

  var _getUsuarios = function(){
    return $http.get(config.baseURL + '/SecurityVraptor/usuario/listarTodos');
  };

  return {
    autenticar: _autenticar,
    getUsuarios: _getUsuarios
  };
});
    
asked by anonymous 19.01.2016 / 17:37

3 answers

2

The way I actually do it is to load it automatically at the beginning of factory and then just make the request where I need it. The only difference is that I use localStorage instead of sessionStorage , but this is easily at your discretion.

Example:

var minhaToken;

function setToken() {
    minhaToken = localStorageService.get('tokenName'); //tokenName é um exemplo do nome da 'data' aramazenada na storage
};

function getToken () {
   return minhaToken;
};

return {
    setToken: setToken(),
    getToken: getToken
};

And when it is necessary to get the token, let's say inside a controller, you just have to make the request:

$scope.token = usuarioAPI.getToken();

This way you can store it inside your service and request it whenever you need it.

Important note:

I've used localStorageService.get since it's the plugin (third-party - not native to AngularJS) that I use. You can choose from the most diverse options you will use, whether it is a third-party plugin or AngularJS itself, see this link . I particularly prefer to use this here because it has more freedom and more options than AngularJS .

Edited:

To send the parameters to your requests, you need to merge them with the ones you already have - I assume it's config.baseUrl if not, you can create a variable inside factory and then move to $http . See:

var configHeader;

function setToken() {
    minhaToken = localStorageService.get('tokenName'); //tokenName é um exemplo do nome da 'data' aramazenada na storage
    if(minhaToken){
        configHeader = {headers:  {
            'token': minhaToken,
            //e/ou outros valores
        }
    } else {
        //Outra lógica caso o usuario ainda não tenha autenticado.
    };
};

return $http.post(config.baseURL + '/SecurityVraptor/usuario/', usuario, configHeader );
return $http.get(config.baseURL + '/SecurityVraptor/usuario/listarTodos', configHeader );

Note: Some time ago I stopped using this way for some internal changes in the work and started to use directly in url , but it is completely at your discretion. I may also be missing out on syntax, as I have not been able to get into this for a long time, but I think you can get the idea already.

In the references of AngularJS in the area of $http has the information of the order of the objects, see: link $ http

    
19.01.2016 / 19:56
2

Use Interceptor to insert the bearer token into all your requests. The following implementation uses localstorage for storage.

app.factory('BearerAuthInterceptor', function ($window, $q) {
    return {
        request: function(config) {
            config.headers = config.headers || {};
            if ($window.localStorage.getItem('token')) {

                config.headers.Authorization = 'Bearer ' + 
                $window.localStorage.getItem('token');
            }
            return config || $q.when(config);
        },
        response: function(response) {
            if (response.status === 401) {
                //  Redirect user to login page / signup Page.
            }
            return response || $q.when(response);
        }
    };
});

// Registra BearerAuthInterceptor no stack do provedor $http.
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('BearerAuthInterceptor');
});

Font .

    
14.09.2016 / 15:32
0

You can configure your requests to always use the token you define.

$http.defaults.headers.common.Authorization = 'Bearer ' + token;
    
14.09.2016 / 15:25