我用来对我的react spa应用程序进行令牌认证。在执行CRUD程序之前,我要检查刷新令牌的到期时间。如果刷新令牌有效,则没问题,但如果无效,我将发送旧的刷新令牌,并在发送原始数据之前从服务器接收新的刷新和访问令牌。 到此为止没有问题。
问题是刷新机制完成了,而没有等待服务器的响应。
currentUser存储令牌值。 我检查令牌的null控制,然后如果到期时间无效,则发送旧的刷新令牌。
此时,函数返回而无需等待 authenticationService.createAccessTokenByRefreshToken 的响应。函数必须等待此函数,因为如果访问令牌无效,则需要新的令牌。
为什么函数不等待就结束?
export function authHeader() {
var authorization = {
Authorization: ''
};
var currentUser = authenticationService.currentUserValue;
if (currentUser && currentUser.token) {
const refreshToken = currentUser.refreshToken;
const expiration = currentUser.expiration;
var moment = require('moment');
var now = moment();
if (moment(now).isAfter(expiration)) {
authenticationService.createAccessTokenByRefreshToken(refreshToken).then((res) => {
authorization.Authorization = `Bearer ${res.data.token}`;
return Promise.resolve(authorization);
});
}
else {
authorization.Authorization = `Bearer ${currentUser.token}`;
return Promise.resolve(authorization);
}
//return { Authorization: `Bearer ${currentUser.token}` };
} else {
return Promise.reject(authorization);
}
}
答案 0 :(得分:5)
if (moment(now).isAfter(expiration)) {
authenticationService.createAccessTokenByRefreshToken(refreshToken).then((res) => {
authorization.Authorization = `Bearer ${res.data.token}`;
return Promise.resolve(authorization);
});
}
此代码块需要一个return语句。目前,它隐式返回undefined。另外,有一件小事:如果您使用的是.then
,则无需执行Promise.resolve(authorization),
,只需返回authorization
。 .then
为您创建了新的承诺。
if (moment(now).isAfter(expiration)) {
return authenticationService.createAccessTokenByRefreshToken(refreshToken)
.then((res) => {
authorization.Authorization = `Bearer ${res.data.token}`;
return authorization;
});
}
答案 1 :(得分:0)
请开始使用async
await
。它使您的工作更轻松,并且具有更少的错误,可读性更强。让我知道以下各项是否对您有用:)
const moment = require("moment");
const authHeader = async () => {
try {
const authorization = {
Authorization: ""
};
const currentUser = authenticationService.currentUserValue;
if (currentUser && currentUser.token) {
const refreshToken = currentUser.refreshToken;
const expiration = currentUser.expiration;
const now = moment();
if (moment(now).isAfter(expiration)) {
const authResponse = await authenticationService.createAccessTokenByRefreshToken(
refreshToken
);
authorization.Authorization = `Bearer ${authResponse.data.token}`;
} else {
authorization.Authorization = `Bearer ${currentUser.token}`;
}
}
return authorization;
} catch (err) {
return err;
}
};
export default authHeader;