很抱歉这个简单的问题我一直在寻找“如何使用它们”的例子而不是“何时使用它们”
基本上我已经完成了创建refreshToken
和销毁它的代码
// Compare token in the database and create a new access token
Player.prototype.validateRefreshToken = function(username, refreshToken) {
return new Promise(async (resolve, reject) => {
try {
let player = await this.col.findOneAsync({ username, refreshToken});
if (player) {
let token = jwt.sign(
{
id: player._id,
username: player.username,
email: player.email,
roles: player.role || "user"
},
globals.jwtSecret,
{
expiresIn: "300"
}
);
return resolve(token);
} else {
return resolve(null);
}
} catch(err) {
console.log("[ERROR]: There was an error trying to validateRefreshToken");
console.log(err);
return reject(err);
}
});
}
// Destroy users refreshToken by generating a new one and not delivering
// it to the client
Player.prototype.rejectToken = function (refreshToken) {
return new Promise(async (resolve, reject) => {
try {
let player = await this.col.findOneAndUpdateAsync(
{ refreshToken },
{ $set: { refreshToken: randtoken.uid(256) },
});
if (player) {
return resolve(true);
} else {
return resolve(false);
}
} catch(err) {
console.log("[ERROR]: There was an error trying to rejectToken");
console.log(err);
return reject(err);
}
});
}
// API Routes
// Check Refresh Token
router.post("/token", async (ctx, next) => {
let username = _.get(ctx.request.body, "username");
let refreshToken = _.get(ctx.request.body, "refreshToken");
if (refreshToken) {
try {
let token = ctx.models.player.validateRefreshToken(username, refreshToken);
if (token) {
ctx.body = { success: true, token };
} else {
ctx.body = { success: false, errors: ["You need to reauthenticate yourself their was an issue getting your refresh token"] };
}
} catch(err) {
console.log(err);
ctx.body = { success: false, errors: ["Internal Server Error"] };
}
} else {
ctx.body = { success: false, errors: ["You are not authenticated"] };
}
});
// Destroy refresh token
router.post("/token/reject", async (ctx, next) => {
let refreshToken = _.get(ctx.request.body, "refreshToken");
if (refreshToken) {
try {
let result = await ctx.models.player.rejectToken(refreshToken);
if (result) {
ctx.body = { success: true };
} else {
ctx.body = { success: false, errors: ["You are not authenticated"] };
}
} catch(err) {
console.log(err);
ctx.body = { success: false, errors: ["Internal Server Error"] };
}
}
});
但我的问题是我不知道我应该post
到/token
E.g。有人向他们自己的个人资料post
发出了/profile/me
个请求,但收到了权限错误,现在该怎么做,我如何自动执行/token
我希望如果它不要求我澄清那就有意义
答案 0 :(得分:0)
我将假设您的应用是移动/桌面应用 - 网络应用通常不需要此支持(尽管我们可以这样做)。您的应用将执行HTTP请求。令牌过期后,HTTP请求将返回401 Unauthorized。陷阱。
在陷阱的代码中,检查您的令牌是否已过期。如果有,请刷新。如果刷新不起作用,请执行完整身份验证。如果令牌尚未过期,请将401一直传递回您的代码,因为还有其他事情正在发生。
在C#/ Xamarin中,您可以使用委派处理程序。在iOS或Android中,您可以将原始HTTP客户端(NSURLSession或HttpClient)包装在执行陷阱的包装器方法中。在JavaScript / React Native / Cordova中,您可以包装执行陷阱的获取调用。