[英]RESTful API access token mechanism
I'm developing a JavaScript/MySQL RESTful API for a business manager system using Express, Body-parser and MySQL.我正在为使用 Express、Body-parser 和 MySQL 的业务管理器系统开发 JavaScript/MySQL RESTful API。 Currently, I am working on access tokens.
目前,我正在研究访问令牌。 Before any API call, the body must include an API key that is being verified by the API.
在任何 API 调用之前,主体必须包含 API 正在验证的 API 密钥。 In every API call function, I first check if the access token exists and if so, the API executes MySQL commands and sends back results.
在每个 API 调用函数中,我首先检查访问令牌是否存在,如果存在,API 将执行 MySQL 命令并返回结果。 The important thing is that I want to create a function that checks whether the access token exists and returns true or false.
重要的是我想创建一个函数来检查访问令牌是否存在并返回 true 或 false。 However, I can't figure out how to return this boolean value from the
conn.query()
method.但是,我不知道如何从
conn.query()
方法返回这个布尔值。 Any help will be very much appreciated, I am desperate.任何帮助将不胜感激,我很绝望。 Here is my code:
这是我的代码:
function checkApiKey(apiKey) {
let sql = "SELECT * FROM apikeys WHERE apikey = '" + apiKey + "'";
conn.query(sql, (err, results) => {
if (err) throw err;
if (results.length > 0) return true;
return false;
});
}
app.get("/api/users",(req, res) => {
if (checkApiKey(req.body.apiKey)) {
let sql = "SELECT * FROM users";
let query = conn.query(sql, (err, results) => {
if (err) throw err;
res.send(results);
});
}
});
However, the checkApiKey()
method returns undefined...但是,
checkApiKey()
方法返回 undefined ...
Your checkApiKey
function returns undefined, because your logic returns true or false within sql's callback function.您的
checkApiKey
函数返回未定义,因为您的逻辑在 sql 的回调函数中返回 true 或 false。
I'd recommend another approach, using checkApiKey
as middleware function:我推荐另一种方法,使用
checkApiKey
作为中间件功能:
const checkApiKey = (req, res, next) => {
conn.query("SELECT * FROM apikeys WHERE apikey = ?", [req.body.apiKey], (err, result) => {
if (err) throw err
if (results)
next() // continue to next router function
else
res.status(403).end('Unauthorized') // resolve with 403
})
}
app.get("/api/users",
checkApiKey, // middleware auth function
(req, res) => {
conn.query("SELECT * FROM users", (err, results) => {
if (err) throw err;
res.send(results)
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.