简体   繁体   English

通过JavaScript / Angular / Ionic Promise获取x-Auth-Token

[英]GET x-Auth-Token via JavaScript/Angular/Ionic Promise

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. 我有一个问题,不知道如何解决...我必须通过基于令牌的身份验证在IonicApp中对用户进行身份验证。 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´sa picture of the Response from the Server (from Firefox). 这是服务器响应的图片(来自Firefox)。 As you can see, the X-Auth-Token is there... here´s the x-auth-token 如您所见,这里有X-Auth-Token ... 这是x-auth-token

Thanks for the help!! 谢谢您的帮助!!

There are lot of articles are available over handling authentication in AngularJS. 在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. 现在,我们将令牌保存在sessionStorage中。 This token can be sent back with each request by at least three ways 至少可以通过三种方式将令牌与每个请求一起发送回去

1. Set header in each request: 1.在每个请求中设置标头:

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

2. Setting defaults headers 2.设置默认标题

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

3. Write Interceptor : 3.写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. 有关详细说明,请参阅AngularJS $ http指南

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.data为null且图像显示标头正在返回时,我建议您检查是否通过以下方式获取数据

response.headers() , response.headers()

if then try with response.headers()["X_AUTH_TOKEN"] . 如果然后尝试使用response.headers()["X_AUTH_TOKEN"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM