我更喜欢分离请求模式并为它们定义单独的身份验证机制。比如……
const express = require('express');
const app = express();
const basicAuth = require('express-basic-auth');
app.use('/web/*', basicAuth({
users: authKeys
}));
app.use('/restrict/*', basicAuth({
users: adminAuthKeys
}));
...任何通过/web/* 访问我的网站的普通用户都定义了单独的身份验证,而不是通过/restrict/* 访问该网站的管理员。 authKeys 包含用户身份验证密钥,adminAuthKeys 包含管理员身份验证密钥。然后我可以根据需要为它们中的每一个定义路由。比如……
// For user
app.get('/web/profile', (req, res) => {
...
...
});
// For user
app.get('/web/post/:id', (req, res) => {
...
...
});
// For admin
app.get('/restrict/stats', (req, res) => {
...
...
});
// For admin
app.get('/restrict/dashboard', (req, res) => {
...
...
});
这里我展示了express-basic-auth 的示例,您可以尝试最适合您的任何身份验证机制。我们通常不会将密码存储在您将在存储库中提交的文件中。密码最好存储在具有适当编码的安全数据库中。对于这个express-basic-auth 示例,如果您可以初始化模式的JSON 对象...
const authKeys = {
"some-user-name": "some-password",
"another-user-name": "another-password",
...
...
}
const adminAuthKeys = {
"some-admin-name": "some-password",
"another-admin-name": "another-password",
...
...
}
...通过在应用程序启动期间从存储中获取数据,然后为用户和管理员初始化 app.use() 块,如使用 express 定义 basicAuth 所示,我认为它应该可以正常工作。
希望这会有所帮助:)