【问题标题】:Simple authentication of REST get call with request interceptors of an Angular service使用 Angular 服务的请求拦截器对 REST get 调用进行简单身份验证
【发布时间】:2015-09-30 00:51:31
【问题描述】:

我想传入对 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 的响应。

【问题讨论】:

  • 如果您要查询的服务器不允许跨源,并且您无法控制服务器添加标头,那么 那个人 i> 控制服务器需要为你做这件事。没有办法绕过此安全功能。
  • 是的,我知道拦截响应并添加标头是一个很长的过程。但无论如何,我如何通过服务调用的请求拦截器通过 401?

标签: javascript angularjs rest angular-services angular-http-interceptors


【解决方案1】:

不是说跨源问题,但这里是如何向请求标头添加一些内容。就我而言,我传入了一个存储在本地存储中的令牌。我们将该值绑定到一个角度常量并将其注入拦截器服务:

.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;
            }
        }
    }

【讨论】:

  • 谢谢。但是我对 Angular 还是很陌生,我不确定如何使用这个常量(结合用户名和密码)来验证我对 api 的请求。我试过让这个常量 - {'username': xxxx, 'password': xxxxx} 但它不起作用,我仍然得到 401。
  • 这个常数只是一个例子。您可能不应该在标题中传递用户名和密码,而是作为登录请求的正文。你想打什么api?它是你的吗?你知道是谁吗?有文档吗?我从未听说过需要用户名和密码作为请求标头一部分的 API。您应该对它的工作原理进行更多研究。
  • 我知道在标题中传递用户名和密码不是一个好主意,但我正在寻找一种方法来通过身份验证,而无需通过提供有效的对来向用户弹出表单代码,以便每次进行呼叫时都使用它进行身份验证。它是一个私有 api,我不是所有者,尽管可能有文档。每当我尝试获取一些数据时,它都会弹出一个用户名和密码的警报对话框(确实有一个有效的)。
猜你喜欢
  • 1970-01-01
  • 2021-07-05
  • 1970-01-01
  • 2023-03-22
  • 2020-01-29
  • 2016-04-04
  • 2017-04-12
  • 1970-01-01
  • 2014-09-19
相关资源
最近更新 更多