首页 > 解决方案 > 如何在nodejs中使用express进行身份验证后授予对文件夹的访问权限?

问题描述

我是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'));并将他们重定向到他们的页面。

有人可以帮忙吗?

标签: javascriptnode.jsexpressbasic-authentication

解决方案


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

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

我刚刚在指定我正在使用的静态文件夹之前放置了身份验证。还有其他人有更好的建议吗?


推荐阅读