角度远程服务器Web服务授权

时间:2015-08-20 10:43:39

标签: javascript angularjs wso2-am

我正在尝试使用我的角度应用从远程Web服务获取数据。由于服务器使用WSO2 api管理器处理请求,我需要传递“授权:承载31363a37a017a4b2e9b1104981ff”以及请求。

我的请求如下:

movieControllers.controller('MovieListCtrl', ['$scope', '$http',
  function($scope, $http) {
    $http.jsonp('http:myserverurl/1.0.0'
      ,{
    headers: {Authorization: 'Bearer AUTH_CODE_HERE'}
  }).success(function(data, status, headers, config) {
      $scope.movies= data;
      $scope.status = status;
 
    }).error(function(error, status, headers, config) {
      $scope.status = status;
     
});

   }]);

但它给了我“未经授权的访问”。看来标题设置不正确。 然后我直接向我的api请求。它不需要任何授权。它工作正常。

我是角色和这个API和Web服务的新手。我需要为Oauth安装额外的模块吗? (我想这个授权的事情是oauth。如果我错了,请纠正我)。任何人都可以指出我正确的方向,这是非常感谢。 感谢。

2 个答案:

答案 0 :(得分:0)

$http.jsonp之前,如果您指定授权。它会起作用

$http.defaults.headers.common. Authorization = 'Bearer AUTH_CODE_HERE'

在这种情况下,您的代码应为 -

movieControllers.controller('MovieListCtrl', ['$scope', '$http',
  function($scope, $http) {

    $http.defaults.headers.common. Authorization = 'Bearer AUTH_CODE_HERE';

    $http.jsonp('http:myserverurl/1.0.0')
    .success(function(data, status, headers, config) {
    $scope.movies= data;
    $scope.status = status;

    }).error(function(error, status, headers, config) {
    $scope.status = status;

   });
}]);

答案 1 :(得分:0)

我还建议创建拦截器,因为拦截器在这里充当请求构建器。

你要做的就是在$ httpProvider中提到拦截器

 var myApp = angular.module('myApp');
 //Set configs
 myApp.config(function($httpProvider){
   //Add dependencyof interceptor  
   $httpProvider.interceptors.push( 'myInterceptor');
 });

现在在工厂中创建一个拦截器

 //Create you interceptor here
 mayApp.factory('myInterceptor', function() {
       return {
          request: function(config) {              
            config.headers[ 'Authorization' ] = 'Bearer AUTH_CODE_HERE';
            return config;
          }
       }
  });

这样,您就可以解决在每个请求中添加授权标头的问题。如果您想要更改配置或想要为每个请求动态生成授权标头,此拦截器也将非常有用。希望这对你有所帮助。干杯!

相关问题