使用AngularJs和Node.js / Express防止直接访问文件

6
使用Angular和Node.js / Express,有没有办法防止直接访问我的部分.html文件,同时仍允许以下路由处理:
我的Angular路由如下:
$stateProvider.state('albums', {
  url: '/albums',
  templateUrl: '/public/albums',
  controller: 'AlbumsCtrl'
});

然后我的Express应用程序会执行以下操作:
app.get('/public/albums', function(req, res){
  res.sendfile('views/partials/albums.html');
});

这一切都运作正常,但键入“mysite.com/public/albums”将允许访问部分 .html 文件。虽然内容是单独加载的,用户需要登录才能查看内容,但我仍然希望防止访问此文件。

2个回答

4
您可能已经找到了答案或其他方法,但是如果您想做类似的事情,实际上有一个解决方法:

思路

您可以使用httpRequestInterceptor在所有来自Angular的请求中添加自定义标题。 在服务器端,您只需检查请求是否包含该标题。 如果没有,则可以重定向或发送错误消息。

代码

客户端(Angularjs):

创建一个拦截器:

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)

当您希望开始避免直接访问时,只需使用以下代码:

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标头

希望这可以帮助到某些人!再见!


只是一个小的规范说明;拦截器代码只适用于Angular 1.1及以上版本。 - Drago96

2

在AngularJS中发出路径为/foo/bar的请求,与输入URL domain.com/foo/bar相同。

你无法阻止其中一个并允许另一个,因为它们最终都是对服务器的请求。

但是,你可以使用中间件来防止未经授权的请求。例如,只有管理员或已登录的用户才能发出请求。

因此,在你的服务器上,你可以编写以下代码:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接