我有这个$ 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应用程序的上下文。
答案 0 :(得分:3)
我无法添加评论,因为我的代表但你在后端做什么来授权用户?如果cookie已签名且包含用户权限,则标题在客户端中可见并不重要,因为它也将在后端API调用中进行验证。
答案 1 :(得分:2)
在此示例中,我使用
HttpRestService
来获取 RESTful API ,请阅读本文首先我们创建一个服务来获取此示例中的配置
getConfigs
我们在应用程序启动时在
getConfigs
中使用app.run
,在获取配置后,我们将所有内容设置为header
作为样本。之后,我们可以通过
userProfile
调用header
来获取controller
新apiUrl
以及安全。在此示例中,您需要定义
var app = angular.module("app", ["HttpRestApp"]);
,它是您的api主机网址,请注意在注销后您可以删除标头,还可以动态定义配置以使您的应用程序更安全。
HttpRestService.js github link
<强> app.js 强>
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.service 强>
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.run 强>
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();
}]);
<强> app.controller 强>
./Sinusbot.sh: line 153: [: missing `]'
./Sinusbot.sh: line 153: [: missing `]'