GET x-Auth-Token via JavaScript/Angular/Ionic Prom

2019-09-10 02:17发布

问题:

I have a problem and don´t know how to solve it... I have to authenticate a user in my IonicApp through a token based authentication. So i have to store the token inside the app, which shouldn´t be a problem... The Problem is: How can i get the token? Here´s my code:

    // Alle Aufrufe an die REST-Api werden hier durchgeführt
    var httpCall = {
        async : function(method, url, header, params, data) {
//          if (url != 'login') {
//              header['X-Auth-Token'] = userTokenFactory.getUserToken();
//          }
            //console.log(header['X-Auth-Token']);
            var ipurl = "IPURL";
            // $http returns a promise, which has a then function, which also returns a promise
            var promise = $http({
                method : method,
                url : ipurl + url,
                //headers : header,
                params : params,
                data : data,
                config : {
                    timeout : 5000
                }
            }).then(function successCallback(response) {
                //console.log("data:" + response.data);
                //console.log("header:" + response.headers);
                console.log("token:" + response.headers['X-AUTH-TOKEN']);
                //console.log(response.data.token);
                console.log("token" + repsonse.token);
                // TRY TO READ THE X_AUTH_TOKEN HERE !!!!!!!!!!!!
                return response;
            }, function errorCallback(response) {
                return response;
            });
            // Return the promise to the controller
            return promise;
        }
    };
    return httpCall;
});

And here´s a picture of the Response from the Server (from Firefox). As you can see, the X-Auth-Token is there... here´s the x-auth-token

Thanks for the help!!

回答1:

There are lot of articles are available over handling authentication in AngularJS. This article is the one perfect suitable in your case.

So you can get token from your request as,

}).then(function successCallback(response) {
    console.log("data:" + response.data);
    $window.sessionStorage.token = response.data.token;
    return response;
}, function errorCallback(response) {
    return response;
});

Now we have the token saved in sessionStorage. This token can be sent back with each request by at least three ways

1. Set header in each request:

`$http({method: 'GET', url: url, headers: {
    'Authorization': 'Bearer ' + $window.sessionStorage.token}
});`

2. Setting defaults headers

`$http.defaults.headers.common['X-Auth-Token'] = 'Bearer ' + $window.sessionStorage.token;`

3. Write Interceptor:

Interceptors give ability to intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests

myApp.factory('authInterceptor', function ($rootScope, $q, $window) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      if ($window.sessionStorage.token) {
        config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
      }
      return config;
    },
    response: function (response) {
      if (response.status === 401) {
        // handle the case where the user is not authenticated
      }
      return response || $q.when(response);
    }
  };
});

myApp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
});

Refer AngularJS $http guide for detailed explanation.

As you are getting response.data null and image demonstrates that headers are being returned, I would suggest you to check if you are getting data with

response.headers(),

if then try with response.headers()["X_AUTH_TOKEN"].