在使用express的nodejs中进行身份验证后,如何授予对文件夹的访问权限?

时间:2018-07-05 20:36:40

标签: javascript node.js express basic-authentication

我是nodejs的新手,并且我一直在寻找解决方案已经有一段时间了,不幸的是没有一个解决方案能够解决我的特定问题。或者至少我不明白。

在我的nodejs项目中,我正在使用一个公用文件夹,其中存储了我的所有html和js文件。

在server.js中,我在公用文件夹之外:

app.use(express.static(__dirname + '/public'));

特定用户(我们称他为Tom)将访问tom-page.html。 另一个用户称为Fred,它将访问fred-page.html。 这些文件及其脚本(javascript)都位于该公用文件夹中。

现在我要做的是用静态密码保护公用文件夹。如果Tom登录,则应将他重定向到/public/tom-page.html,对于Fred,应将其重定向到/public/fred-page.html。他们应该有权访问该文件夹中的所有其他文件。

我到目前为止所做的:

const express = require('express');
const app = express();
var basicAuth = require('basic-auth');
var is_tom = false;

var auth = function(req, res, next) {
  function unauthorized(res) {
    res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
    return res.send(401);
  };

  var user = basicAuth(req);

  if (!user || !user.name || !user.pass) {
    return unauthorized(res);
  };

  if (user.name === 'fred' && user.pass === 'fred-pwd') {
    is_tom = false;
    return next();
  } else if (user.name === 'tom' && user.pass === 'tom-pwd') {
    is_tom = true;
    return next();
  } else {
    return unauthorized(res);
  }
};

const http = require('http');
server = http.createServer(app);

app.get('/', auth, function(req, res) {
  if (is_tom) {
    res.send('hi tom');
  } else {
    res.send('hi fred');
  }
});

这有效。但是我不知道如何授予他们对公用文件夹(也称为app.use(express.static(__dirname + '/public'));)的访问权限,以及如何将他们重定向到他们的页面。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

我刚刚找到了一种可行的解决方案:

app.use(auth, express.static(__dirname + '/public'));

我只是在指定要使用的静态文件夹之前放入auth。 还有其他人有更好的建议吗?

答案 1 :(得分:0)

您可以将所有页面放在WEB-INF文件夹中,此目录仅可用于您的应用程序。如果用户已登录,则可以将其发送到该文件夹​​内的文件中。