Angular远程服务器web服务授权

Angular remote server web service authorization

本文关键字:服务 授权 web 服务器 Angular      更新时间:2023-09-26

我试图从远程web服务与我的角应用程序获取数据。由于服务器使用WSO2 api管理器来处理请求,我需要通过"授权:承载31363a37a017a4b2e9b1104981ff"连同请求。

My request looks follows

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。它不需要任何授权。它工作得很好。

我对angular和API和web服务都是新手。我需要为Oauth安装额外的模块吗?(我想这个授权是真的。如果我说错了请指正)。谁能给我指出正确的方向,非常感谢。谢谢。

如果分配了Authorization,则在$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;
   });
}]);

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

你所要做的就是在$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;
          }
       }
  });

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