Ajax用旧的认知令牌解雇了。 (新的刷新令牌尚未恢复)

时间:2019-12-09 09:30:00

标签: javascript token amazon-cognito

当旧的congito令牌过期时,我遇到了问题,但是ajax仍然使用旧的令牌触发。它不会等到新令牌返回。我们很难找到解决方案。我们尝试使ajax进入睡眠状态,直到新的令牌返回到以下代码中,但没有起作用。任何帮助将不胜感激。

// Cognito user access control
var poolData = {
    UserPoolId: '`xxxxxxxxxxxxxxxxx',
    ClientId: 'zzzzzzzzzzzzzzz'
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUserPool(poolData).getCurrentUser();
// console.log(cognitoUser)
var idToken = null;
var refreshObj = null;
if (cognitoUser != null) {
    cognitoUser.getSession(function (err, session) {
        if (err) {
            console.log(err);
            return;
        }
        refreshObj = session.getRefreshToken();
        refresh();
    });
} else {
    var currentUrl = window.location.href;
    var baseUrl = window.location.origin;
    // redirect to login page with paramater 
    //window.location.href = baseUrl + '/login.html?redirect=' + currentUrl;
    if (currentUrl.indexOf("login.html") < 0) {
        window.location.href = baseUrl + '/totallane_dev/login.html?redirect=' + currentUrl;
    }
}

function getIdToken() {

    cognitoUser.getSession(function (err, session) {
        if (err) {
            console.log(err);
            return;
        }
        idToken = session.getIdToken().getJwtToken();
    });

    var count = 0;
    while(!checkToken() && count != 10){
        sleep(200);
        count = count + 1;
    }
    return idToken + "_" + getTotallaneToken();
}
function sleep(miliseconds) {
    var currentTime = new Date().getTime();
    while (currentTime + miliseconds >= new Date().getTime()) {
    }
}

function checkToken() {
    if (cognitoUser == undefined || cognitoUser == null) {
       // forceRefresh();
        return false;
    }
    var signInUserSession = cognitoUser.getSignInUserSession();
    if (signInUserSession == null || signInUserSession == undefined) {
       // refresh();
        return false;
    } else {
        return signInUserSession.isValid();
    }
}



function forceRefresh() {
    console.log("refresh on:" + new Date().toString());
    if (cognitoUser == null || cognitoUser == undefined) {
        cognitoUser = new AmazonCognitoIdentity.CognitoUserPool(poolData).getCurrentUser();
    }
    if (refreshObj != null) {
        refresh();
    } else {
        cognitoUser.getSession(function (err, session) {
            if (err) {
                console.log(err);
                return;
            }
            refreshObj = session.getRefreshToken();
            refresh();
        });
    }

}

function refresh() {
    cognitoUser.refreshSession(refreshObj, function (error, newSession) {
        if (error) {
            console.log(error);
            return;
        }
        idToken = newSession.getIdToken().getJwtToken();
        refreshObj = newSession.getRefreshToken();
        setCookie(idToken, newSession.idToken.payload.exp);
    });
}
setInterval('forceRefresh()', 10 * 60 * 1000);


0 个答案:

没有答案