登录成功后重定向express js路由
Redirect express js route after a successful login
我正在开发 express js 应用程序,第一页是登录/注册页面。在 login.js
我已经使用 passport
和 JWT
来验证用户并将成功登录的用户重定向到应用程序的主页:
function login(req, res, next){
User.forge({ email: req.body.email }).fetch().then(result => {
if (!result) {
return res.status(401).send('user not found');
}
result.authenticate(req.body.password).then(user => {
const payload = { id: user.id };
const token = jwt.sign(payload, process.env.SECRET_OR_KEY);
console.log(res.statusCode); // just for testing
res.redirect('/mypage');
}).catch(err => {
return res.status(401).send({ err: err });
});
});
}
mypage
我有
的快递路线
app.get('/mypage', (req, res) => {
res.sendFile(path.join(__dirname + '/view/mypage.html'));
}
});
它有效,但问题是甚至没有登录用户可以通过 localhost:PORT/mypage
.
访问该路由
首先,重定向到另一条路线是否可行?成功登录后重定向到另一个呈现页面的最佳和适当方法是什么?
添加一个中间件守卫,检查请求是否确实在其 header 中包含令牌。
这是一个通用示例:
/* ================================================
INFO: @MIDDLEWARE - Used to grab user's token from headers
================================================ */
router.use((req, res, next) => {
// INFO: Getting the generated token from headers
const token = req.headers['authorization']; // Create token found in headers
// INFO: Check if token was found in headers
if (!token) {
let content =
`<body style="margin: 0px;">
<div style="width: -webkit-fill-available; height: -webkit-fill-available;">
<div class="col-sm-12 " style="padding-top: 1em; padding-left: 1em;">
<h3 style="color:#666666;">Direct navigation via the browser's URL-bar forbidden!</h3>
<p style="color:#666666;">Please use the navigation provided by the application only.</p>
<a style="color:#800101; text-decoration:none; font-weight:bold;" href="http://${stdoutIP}" target="_self">Back to Login</a>
</div>
</div>
</body>`;
res.send(content);
}
else {
// INFO: Verify the token is valid
jwt.verify(token, "myVerySecretSecret", (err, decoded) => {
// INFO: Check if error is expired or invalid
//console.log("token verification:",token);
if (err) {
// INFO: Return error for token validation
res.json({ success: false, message: 'Token invalid: ' + err });
} else {
// INFO: Create global variable to use in any request beyond
req.decoded = decoded;
// INFO: Exit middleware
next();
}
});
}
});
我正在开发 express js 应用程序,第一页是登录/注册页面。在 login.js
我已经使用 passport
和 JWT
来验证用户并将成功登录的用户重定向到应用程序的主页:
function login(req, res, next){
User.forge({ email: req.body.email }).fetch().then(result => {
if (!result) {
return res.status(401).send('user not found');
}
result.authenticate(req.body.password).then(user => {
const payload = { id: user.id };
const token = jwt.sign(payload, process.env.SECRET_OR_KEY);
console.log(res.statusCode); // just for testing
res.redirect('/mypage');
}).catch(err => {
return res.status(401).send({ err: err });
});
});
}
mypage
我有
app.get('/mypage', (req, res) => {
res.sendFile(path.join(__dirname + '/view/mypage.html'));
}
});
它有效,但问题是甚至没有登录用户可以通过 localhost:PORT/mypage
.
首先,重定向到另一条路线是否可行?成功登录后重定向到另一个呈现页面的最佳和适当方法是什么?
添加一个中间件守卫,检查请求是否确实在其 header 中包含令牌。
这是一个通用示例:
/* ================================================
INFO: @MIDDLEWARE - Used to grab user's token from headers
================================================ */
router.use((req, res, next) => {
// INFO: Getting the generated token from headers
const token = req.headers['authorization']; // Create token found in headers
// INFO: Check if token was found in headers
if (!token) {
let content =
`<body style="margin: 0px;">
<div style="width: -webkit-fill-available; height: -webkit-fill-available;">
<div class="col-sm-12 " style="padding-top: 1em; padding-left: 1em;">
<h3 style="color:#666666;">Direct navigation via the browser's URL-bar forbidden!</h3>
<p style="color:#666666;">Please use the navigation provided by the application only.</p>
<a style="color:#800101; text-decoration:none; font-weight:bold;" href="http://${stdoutIP}" target="_self">Back to Login</a>
</div>
</div>
</body>`;
res.send(content);
}
else {
// INFO: Verify the token is valid
jwt.verify(token, "myVerySecretSecret", (err, decoded) => {
// INFO: Check if error is expired or invalid
//console.log("token verification:",token);
if (err) {
// INFO: Return error for token validation
res.json({ success: false, message: 'Token invalid: ' + err });
} else {
// INFO: Create global variable to use in any request beyond
req.decoded = decoded;
// INFO: Exit middleware
next();
}
});
}
});