使用Angular服务的请求拦截器对REST get调用进行简单的身份验证

Simple authentication of REST get call with request interceptors of an Angular service

本文关键字:调用 get 简单 REST 身份验证 服务 Angular 请求 使用      更新时间:2023-09-26

我想传递一个用户名和密码组合,这是对api进行REST调用所需要的。

Controller.js

var app = angular.module('myApp', []);
//The service to put the interceptor configuration on (not on all $http method calls)
app.factory('getCallsApi', ['$http', function($http) {
    return {
        get: function(callback) {
            $http.get(/* REST URI */).success(function(data) {
                callback(data);
            });  
        }
    }
}]);
var Interceptor = function($q) {
    return {
        request: function(config) {
            //TODO: Pass in username and password (hardcoded) to get through authentication
        },
        requestError: function(rejection) {
        },
        response: function(config) {
            //TODO: ADD Cross origin headers
        },
        responseError: function(rejection) {
        }
    }
}
app.config(['$httpProvider', function($httpProvider) {  
    $httpProvider.interceptors.push(Interceptor);
}]);
myApp.controller('appController', ['$scope','getCallsApi', function($scope, getCallsApi) {
  getCallsApi.get(function(data) {
    console.log(data);
  });
}]);

我目前在控制台中收到两个错误。首先是401状态,表示未授权访问,并且在请求的资源上没有找到跨源标头。我不能自己把X源标头放在请求的资源上,因为我没有编辑API响应的权利。

不是说交叉原点问题,而是如何在请求头中添加一些东西。在我的例子中,我传入了一个存储在localstorage中的令牌。我们把这个值绑定到一个angular常量中,并把它注入到拦截器服务中:

.constant('AUTH_TOKEN', localStorage.getItem('myapp.authToken'))

在你的拦截器中:

    var Interceptor = function ($q) {
        return {
            request: function (config) {
                if (AUTH_TOKEN) {
                    config.headers['Authorization'] = 'Token ' + AUTH_TOKEN;
                }
                return config;
            }
        }
    }