Pass Token by header to each Angularjs request

Asked

Viewed 2,578 times

4

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

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

3 answers

3


The way I currently do it is to automatically load it at the beginning of the factory and then just make the request where I need it. The only difference is that I use the localStorage instead of sessionStorage, but that 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 you need to get the token, say within a controller, you just have to make the request:

$scope.token = usuarioAPI.getToken();

This way you can store it within your service and request whenever necessary.


Important remark:

I used localStorageService.get because it is the plugin (third party - not native to Angularjs) that I use. You can choose among the most diverse options which you will use, be it a third party plugin or own AngularJS, see this link. I personally prefer use this one, because it has more freedom and more options than the AngularJS.


Edited:

To send the parameters in your requests, you need to merge them with the ones you already have - I assume you are the config.baseUrl if not, you can create a variable within the factory and then move on to the $http. Behold:

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

Obs.: A while ago I stopped using this way for some internal changes at work and started using directly in the url, but it’s completely up to you. I may also be missing syntax, because I haven’t touched it in a while, but I think you can get the idea now.

In the references of AngularJS in the area of $http has information of the order of the objects, see: https://docs.angularjs.org/api/ng/service/$http

  • I got it, I did it with an Interceptor but I’m having problems. Thus all requests are intercepted and the first request that is the login and the one that saves the data in the sessionStorage could not be intercepted

  • And how do you pass the token in the header to each request?

  • What if you move the login to a separate service without an Interceptor? I, for example, own the module auth that manages only authentication/account creation. From there, I use this logic, to get the token (but inside the .run) and do the checks from there right in the resolve of my state. When to header, I will update the answer.

  • True, I will try to leave the login in a separate service.

  • @Techies edited the answer.

  • Thanks for the reply, I managed to resolve. I will try to improve the code.

  • 1

    Great! Good work!

Show 2 more comments

3

Use a Interceptor to insert the bearer token in 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');
});

Source.

0

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

$http.defaults.headers.common.Authorization = 'Bearer ' + token;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.