阻止使用AngularJs和Node.js / Express直接访问文件
使用Angular和Node.js / Express,是否有办法阻止直接访问我的部分.html文件,同时仍然允许以下路由处理:
我的Angular路线如下所示:
$stateProvider.state('albums', { url: '/albums', templateUrl: '/public/albums', controller: 'AlbumsCtrl' });
那么我的快递应用程序做以下几点:
app.get('/public/albums', function(req, res){ res.sendfile('views/partials/albums.html'); });
这一切工作正常,但键入“mysite.com/public/albums”允许访问部分.html文件。 由于内容被单独加载,用户需要login才能看到任何内容,但是我仍然希望以某种方式阻止访问此文件。
你可能自己find了一个答案或不同的方法,但是如果你想做这样的事情,实际上有一个解决方法:
这个想法
您可以使用httpRequestInterceptor在所有来自angular度的请求上添加自定义标头。 在服务器端,您可以检查请求是否包含该标头。 如果没有,则可以redirect或发送错误消息。
代码
客户端(Angularjs):
创build一个拦截器:
myApp.factory('httpRequestInterceptor', function () { return { request: function (config) { config.headers['x-custom-header-name'] = 'something' return config } } });
将拦截器添加到$ httpProvider拦截器中:
myApp.config( function ($httpProvider) { $httpProvider.interceptors.push('httpRequestInterceptor') });
服务器端(node.js)
在开始避免直接访问的时候,只需要input以下代码:
app.use(function (req, res, next) { if (!req.headers['x-custom-header-name']) { res.redirect('/'); //Or just do what you want to } next(); });
或者,如果您想避免仅在一个或某些路线上进行访问,则可以修改代码更改
app.use(function (req, res, next) ...
同
app.use( 'route/no-direct-access', function (req, res, next) ...
拦截器的代码来自这个stackoverflow问题:
在AngularJS中设置应用程序范围的HTTP标题
希望这可以帮助别人! 再见!
在AngularJS中为path /foo/bar
提出请求与inputURL domain.com/foo/bar
相同。
你不能阻止和允许另一个,因为最后 – 他们是对服务器的请求。
你可以做的是防止使用中间件的未经授权的请求。 例如,仅当用户是pipe理员或仅当用户已经login时。
所以,在你的服务器上,你可以写一个代码,如:
function ensureAuthenticated (request, response, next) { //Custom code - If request is authenticated return next(); //if Not res.send(403, "Forbidden"); }; app.get('/public/albums', ensureAuthenticated, function (req, res) { //res.sendfile(filepath); });