我最近在LoopBack3中启动了一个项目,并且正在使用集成的回送身份验证,一旦时间到,我就需要刷新AccessToken。
我已经在互联网上搜索了回送文档,但没有找到一种方法。我试图在server / server.js中制作一个中间件,并直接使用连接器(MySql)进行查询,并更新“ created”字段,但它似乎进行了更新而没有错误,但它并没有改变数据库中的值
// Array with the paths that I want to apply the middleware
var aPaths = [...];
//Middleware in server.js
app.use(aPaths,async function (req, res, next) {
const connector = app.dataSources.myDataSource.connector;
if (!req.headers.authorization || req.headers.authorization == '') {
return res.status(403).json({ error : {code:'AUTHORIZATION_REQUIRED',statusCode:401} });
}else{
var sql = "SELECT * FROM AccessToken where id = '" + req.headers.authorization + "'";
connector.execute(sql, null, async (err, resultObject) => {
if (!err && resultObject) {
if (resultObject.length > 0) {
const date1 = new Date(Date.now());
const date2 = new Date(String(resultObject[0].created));
var diffTime = Math.abs(date1.getTime() - date2.getTime());
// Difference between the creation date and the current date (In minutes)
diffTime = diffTime / (1000 * 60);
// Token validity in minutes
var token_validity = resultObject[0].ttl / 60;
// If the token is still valid, do nothing
if (token_validity > diffTime) {
next();
}else{
// If the token expired in less than 10 minutes I want to refresh it
if ((diffTime - token_validity) < 10) {
var sql = "UPDATE AccessToken SET created= NOW() WHERE id = '" + req.headers.authorization + "'";
console.log("SQL: " + sql);
try {
await connector.execute(sql, null, (err) =>{
if (error){
console.log(err);
return res.status(401).json({ error : {code:'AUTHORIZATION_REQUIRED',statusCode:401} });
} else {
next();
}
});
} catch(err) {
console.log(err);
return res.status(401).json({ error : {code:'AUTHORIZATION_REQUIRED',statusCode:401} });
}
} else {
return res.status(401).json({ error : {code:'AUTHORIZATION_REQUIRED',statusCode:401} });
}
}
} else {
return res.status(401).json({ error : {code:'AUTHORIZATION_REQUIRED',statusCode:401} });
}
} else {
return res.status(401).json({ error : {code:'AUTHORIZATION_REQUIRED',statusCode:401} });
}
});
}
});
如果令牌在不到10分钟内过期,我想更新令牌,与此同时我得到:
错误:无效的访问令牌
因为它继续执行next(),并且令牌已过期,因此被环回删除
答案 0 :(得分:0)
只需针对特定用户更新accessToken表中的创建字段。
转到server.js文件并更新以下代码:
MEMBER OF
答案 1 :(得分:0)
首先,只要accessToken没有过期,就需要考虑刷新accessToken。如果仅在10分钟以内过期时才刷新accessToken,则十分钟内没有任何操作时,用户将被注销。
server.js
app.use(function(req, res, next) {
let token = req.accessToken;
if (!token) return next();
let now = new Date();
// for performance, you can drop it
if (now.getTime() - token.created.getTime() < 6000) return next();
token.updateAttribute('created', now, next);
});
您不需要执行SQL查询,而是可以使用此代码。
另外,如果您想更改默认值ttl
,也可以在model-config
model-config.json
...
"user": {
"dataSource": "mysqlDs",
"public": true,
"options": {
"ttl": 1209600
}
},
...