【发布时间】:2021-09-06 14:25:30
【问题描述】:
晚上好!我会先说如果这不可能,我愿意接受其他建议。
我正在使用 MERN 堆栈创建一个非常简单的发票应用程序。我只想通过在路由之前添加一些中间件来保护我在后端的路由。我正在使用 Auth0 进行身份验证。我想对标头referer URL 做一个简单的比较,但是当页面第一次被重定向时,它有authorization_code 和state 附加到 URL,然后当页面刷新时它的正常 URL 没有附上代码和状态。有没有办法获得状态和授权码?我也尝试过 cookie 验证,但问题是在重定向完成之前没有给出 cookie,所以中间件一直在发送错误。
我是应用程序身份验证层的新手,所以如果有更好的方法可以做到这一点,我会全力以赴。我也在考虑改用访问令牌,只是将获取访问令牌的逻辑放在中间件中。
// server.js
app.use(
expressSession({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
})
);
app.use(express.json());
app.use(cors());
app.use(express.static(path.join(__dirname, 'build')));
app.use('/', cookieValidationMiddleware,refererValidationMiddleware, StoreInvoiceRouter); // route that has the middleware
app.use('/', saveLoggedInUserMiddleware, UserInvoicesRouter);
app.use('/', UpdateUserProfileRouter);
app.get('*', async (req,res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
//CookieValidation (not actually the cookie)
var cookie = require('cookie');
const cookieValidation = (req,res,next) => {
const headerHost = req.headers.host;
const host = `localhost:8080`;
if(headerHost === host) {
console.log('[cookieValidation] Header: hosts match');
next();
} else {
console.log('[cookieValidation] Header: Hosts do not match');
return;
}
};
module.exports = cookieValidation;
// RefererValidation (not referer validation anymore)
// TODO Change the code below to get the authorization code from the URL to use or find another method to protect this route.
const refererValidation = (req,res,next) => {
if(req.sessionID) {
console.log('[refererValidation] Session Valid');
next()
} else {
console.log('[refererValidation] Session IDs do not match');
return;
}
};
module.exports = refererValidation;
【问题讨论】:
-
我认为,如果您展示您目前拥有的相关代码,我们可以提供更好的帮助。
-
我添加了相关代码。一个重要的注意事项是我使用 Auth0 进行身份验证。
标签: node.js reactjs express authentication auth0