我有这个$http请求拦截器
app.config(function($httpProvider) {
$httpProvider.interceptors.push(function() {
return {
request: function(req) {
// Set the `Authorization` header for every outgoing HTTP request
req.headers['cdt_app_header'] = 'tamales';
return req;
}
};
});
});
有什么方法可以为每个$http请求添加一个标头或cookie,但保持标头值安全/在JavaScript中不可见?
我们可以使用此标头添加一个混淆层,以防止轻松访问我们的 API 端点,但我想知道一个更真正安全的解决方案。
Cookie 用于安全会话,这些会话更安全,因为它们无法使用 JavaScript 访问。假设我们有一个用户可以使用前端代码执行此请求:
GET /api/users
我们真的不希望他们能够在没有额外信息的情况下使用 cURL 或浏览器发出简单的请求。我们给他们的 cookie 将使他们能够使用浏览器地址栏向/api/users 发出 GET 请求,但是如果我们添加另一个 cookie 或标头的要求,那么我们可以阻止他们以我们并不真正希望他们使用的格式访问授权的端点。
换句话说,我们希望尽最大努力为他们提供访问权限,但仅限于前端 Angular 应用程序的上下文中。
由于我的代表,我无法添加评论,但是您在后端做什么来授权用户?如果 cookie 已签名并包含用户权限,则标头在客户端中可见并不重要,因为它也将在后端 API 调用中得到验证。
示例中,我使用了
HttpRestService
来获取RESTful API,请阅读这篇文章首先,我们创建一个服务来获取此示例中的配置
getConfigs
我们在应用程序启动时在
app.run
中使用getConfigs
,获取配置后,我们将它们全部作为示例在header
中设置。之后,我们可以使用新
header
获得userProfile
,也可以如您所见,通过从我们的controller
调用它来确保安全。在此示例中,您需要定义
apiUrl
,它是您的 API 主机 URL,请记住,注销后您可以删除标头,也可以动态定义配置以使您的应用程序更安全。
HttpRestService.jsgithub链接
应用.js
var app = angular.module("app", ["HttpRestApp"]);
应用服务服务
app.service("service", ["$http", "$q", "RestService", function (http, q, restService) {
this.getConfigs = function () {
var deferred = q.defer();
http({
method: "GET",
async: true,
headers: {
"Content-Type": "application/json"
},
url: "you url to get configs"
}).then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.resolve(error);
});
return deferred.promise;
}
var api = {
user: "User" //this mean UserController
}
//get user with new header
//this hint to your api with this model "public Get(int id){ return data; }"
//http://localhost:3000/api/users/123456
this.getUserProfile= function(params, then) {
restService.get(params, api.user, true).then(then);
}
}]);
应用运行
app.run(["RestService", "service", function (restService, service) {
var header = {
"Content-Type": "application/json"
}
//get your configs and set all in the header
service.getConfigs().then(function (configs) {
header["systemId"] = configs.systemId;
});
var apiUrl = "http://localhost:3000/";
restService.setBaseUrl(apiUrl, header);
}]);
应用程序控制器
app.controller("ctrl", ["$scope", "service", function ($scope, service) {
$scope.getUserProfile = function () {
//this is just sample
service.getUserProfile({ id: 123456 }, function (data) {
$scope.user = data;
});
}
$scope.getUserProfile();
}]);