我有这个$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访问,因此Cookie更加安全。假设我们有一个用户,他可以使用前端代码执行此请求:
GET /api/users我们真的不希望他们能够在没有额外信息的情况下使用cURL或浏览器发出简单的请求。我们为他们提供的cookie将使他们能够使用浏览器地址栏向/api/用户发出GET请求,但如果我们添加了另一个cookie或标头的要求,那么我们可以阻止他们以我们不希望他们真正使用的格式访问授权的端点。
换句话说,我们希望尽最大努力让他们访问,但仅限于在前端Angular应用程序的上下文中。
发布于 2017-06-10 09:48:00
我不能添加评论,因为我的代表,但您在后端做什么授权用户?如果cookie是签名的,并且包含用户权限,那么标头在客户机中是否可见并不重要,因为它也会在后端API调用中进行验证。
发布于 2017-06-10 14:26:28
在此示例中,我使用了HttpRestService来获取RESTful
,请阅读本文
首先,我们创建一个服务来获取我们的配置,在此示例中为getConfigs
当应用程序启动时,我们在app.run中使用getConfigs,在获得配置后,我们将它们都设置在header中作为示例。
在那之后,我们可以通过新的header获得userProfile,也可以通过从我们的controller调用它来确保安全,如你所见。
在此示例中,您需要定义apiUrl,它是您的api主机url,请记住,在注销后,您可以删除标题,也可以动态定义您的配置,以使您的应用程序更安全。
HttpRestService.js github link
app.js
var app = angular.module("app", ["HttpRestApp"]);app.service
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
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
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();
}]);https://stackoverflow.com/questions/44468675
复制相似问题