简体   繁体   English

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

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

I want to pass in a username and password combination that is needed to make a REST call to an api. 我想传递对api进行REST调用所需的用户名和密码组合。

Controller.js 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);
  });
}]);

I am currently receiving two errors in the console. 我目前在控制台中收到两个错误。 First is a 401 status for unauthorized access and an error about cross origin headers not found on the requested resource. 首先是未经授权访问的401状态,以及在所请求的资源上找不到有关跨源标头的错误。 I cannot put the X origin headers on the requested resource myself because I dont have rights to edit that response of the API. 我自己不能将X原始标头放在请求的资源上,因为我无权编辑API的响应。

Not speaking for the cross origin issue, but here is how to add something to the request headers. 不是说跨源问题,而是这里介绍如何向请求标头添加内容。 In my case, I pass in a token that is stored in localstorage. 就我而言,我传入了存储在本地存储中的令牌。 We bind that value to an angular constant and inject it to the interceptor service: 我们将该值绑定到一个角度常数,并将其注入到拦截器服务中:

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

And in your interceptor: 在拦截器中:

    var Interceptor = function ($q) {
        return {
            request: function (config) {

                if (AUTH_TOKEN) {
                    config.headers['Authorization'] = 'Token ' + AUTH_TOKEN;
                }
                return config;
            }
        }
    }

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

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