【发布时间】:2021-07-28 17:53:46
【问题描述】:
我是 JWT 身份验证的新手,我需要保护 Express 路由。在添加身份验证之前,我执行以下操作以使用 Express 返回 HTML 页面:
var cache = {};
app.get('/my_page', function (req, res) {
serveStatic(res, cache, './public/default/my_page.html');
});
其中 serveStatic 是:
var send404 = function (response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: Resource not found.');
response.end();
}
var sendFile = function(response, filePath, fileContents) {
var mimeType = mime.lookup(path.basename(filePath));
response.writeHead(200, {"content-type": mimeType});
response.end(fileContents);
}
var serveStatic = function(response, cache, absPath) {
if (cache[absPath]) {
sendFile(response, absPath, cache[absPath]);
} else {
fs.exists(absPath, function(exists) {
if (exists) {
fs.readFile(absPath, function(err, data) {
if (err) {
send404(response);
} else {
cache[absPath] = data; // Cache the file
sendFile(response, absPath, data); // Serve the file
}
});
} else {
send404(response);
}
});
}
}
用户点击按钮访问页面:<button type="button" onclick="window.location='my_page'">Go</button>
我添加了如下认证:
// In /middleware/auth file
const jwt = require("jsonwebtoken");
const dotenv = require('dotenv');
dotenv.config();
module.exports = function(req, res, next) {
const token = req.header("Authorization");
if (!token) {
return res.status(401).json({
message: "Auth Error",
errorCode: 401,
redirectUrl: "/"
});
}
try {
const decoded = jwt.verify(token, process.env.SECRET);
req.user = decoded.user;
next();
} catch (e) {
res.status(500).send({
message: "Invalid Token",
errorCode: 500,
redirectUrl: "/"
});
}
};
我把路由管理改成:
const auth = require("./middleware/auth");
app.get('/licenses',
auth,
function (req, res, next) {
serveStatic(res, cache, './public/default/my_page.html');
}
);
我更改了 onclick 按钮以调用从 cookie 中检索 JWT 并将其与请求一起发送的函数。
<button type="button" onclick="openPage()">Go</button>
var openPage= function() {
if (document.cookie != "") {
var token = getCookie("token");
if (token != "") {
$.ajax({
type: "GET",
url: "/my_page",
data: {},
dataType: "json",
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', token);
},
success: function(msg) {
},
error: function($xhr, textStatus, errorThrown) {
}
});
} else {
console.error('token is empty');
}
} else {
console.error('cookie is empty');
}
}
身份验证过程很好,但客户端收到一条消息,其中包含 my_page.html 代码在其 responseText 属性中。有没有办法让它表现得像我添加身份验证之前的样子?
【问题讨论】:
标签: node.js express jwt authorization