【问题标题】:AngularJS, how to pass API key to service in order to authenticate?AngularJS,如何将 API 密钥传递给服务以进行身份​​验证?
【发布时间】:2015-09-02 11:58:06
【问题描述】:

首先,这是我的服务,用于检索 API 密钥的承诺:

app.factory('AuthenticationService', function($http) {
        return {
        getData: function() {
            return $http.get('http://game.mywebsite.com/start/?token=2132')
                .then(function(result) {
                    return result.data;
            }
        );
    }
}

在我的控制器中,我绑定了密钥:

AuthenticationService.getData()
    .then(function(result) {
        $scope.apiKey = result;            
});

我想知道将我从服务器检索到的 API 密钥传递到哪里。我有一个控制器实现:

 DrawService.getData($scope.apiKey)
    .then(function(result) {
        $scope.numbers = result.data;
});

还有服务:

app.factory('DrawService', function($http) {
        return {
            getData: function(apiKey) {
            return $http.get('http://game.mywebsite.com/draw/')
                .then(function(result) {
                    return result.data;
        });
    }
}

我仍然无权从服务器访问数据。我想知道在哪里传递这个 apiKey 参数才能获得授权,考虑到我有更多的服务应该返回一些数据,但首先需要授权?

【问题讨论】:

  • 你的API key是请求头还是需要参数?
  • 必须是参数。

标签: ajax json angularjs


【解决方案1】:

bltzrrr,game.mywebsite 是你的应用程序吗?

如果是这样,您需要知道参数名称才能正确请求它。

假设它是 apiKey,它看起来像:

$http.get('http://game.mywebsite.com/draw/', {params: {apiKey: 'apiKey'}});

希望对你有帮助

【讨论】:

  • 是的。在服务器端,我完全不知道我应该在哪里传递这个 API 密钥。我已经尝试过您的解决方案,但我仍然未经授权。
  • bltzrrr,您的服务(无论是 Java、Python 等)是否接收任何参数?
【解决方案2】:

这取决于您的服务器实施了何种授权

查看您的代码,我认为您需要在服务标头中传递 api 令牌才能访问数据。

您可以将数据传递到每个服务的标头中

 app.factory('DrawService', function($http) {
            return {
                getData: function(apiKey) {
                 return $http.get('http://game.mywebsite.com/draw/',{
                     headers: { "Authorization": "Bearer APIKEY"}
                   }).then(function(result) {
                        return result.data;
                  });
            }
    }

或者您可以将其全局设置为每个服务调用的标头

app.factory('DrawService', function($http) {
        return {
            getData: function(apiKey) {
             $http.defaults.headers.common.Authorization = "Bearer APIKEY";
            return $http.get('http://game.mywebsite.com/draw/')
                .then(function(result) {
                    return result.data;
        });
    }
}

授权可以是不记名、基本或摘要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 2016-03-22
    • 2017-06-07
    • 2011-12-10
    相关资源
    最近更新 更多