我有一段使用keycloak和JS的代码。 除了刷新令牌方法之外完全正常工作的代码必须在令牌过期时从外部调用。如何在过期时自动刷新令牌。
var keycloak = Keycloak('keycloak.json');
keycloak.init({ onLoad: 'login-required' })
.success(reloadData)
.error(function(errorData) {
document.getElementById('customers').innerHTML = '<b>Failed to load data. Error: ' + JSON.stringify(errorData) + '</b>';
});
var loadData = function () {
document.getElementById('subject').innerHTML = keycloak.subject;
if (keycloak.idToken) {
document.getElementById('profileType').innerHTML = 'IDToken';
document.getElementById('username').innerHTML = keycloak.idTokenParsed.preferred_username;
document.getElementById('email').innerHTML = keycloak.idTokenParsed.email;
document.getElementById('name').innerHTML = keycloak.idTokenParsed.name;
document.getElementById('givenName').innerHTML = keycloak.idTokenParsed.given_name;
document.getElementById('familyName').innerHTML = keycloak.idTokenParsed.family_name;
} else {
keycloak.loadUserProfile(function() {
document.getElementById('profileType').innerHTML = 'Account Service';
document.getElementById('username').innerHTML = keycloak.profile.username;
document.getElementById('email').innerHTML = keycloak.profile.email;
document.getElementById('name').innerHTML = keycloak.profile.firstName + ' ' + keycloak.profile.lastName;
document.getElementById('givenName').innerHTML = keycloak.profile.firstName;
document.getElementById('familyName').innerHTML = keycloak.profile.lastName;
}, function() {
document.getElementById('profileType').innerHTML = 'Failed to retrieve user details. Please enable claims or account role';
});
}
var url = '/database/customers';
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Authorization', 'Bearer ' + keycloak.token);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
var users = JSON.parse(req.responseText);
var html = '';
for (var i = 0; i < users.length; i++) {
html += '<p>' + users[i] + '</p>';
}
document.getElementById('customers').innerHTML = html;
console.log('finished loading data');
}
}
}
req.send();
};
var loadFailure = function () {
document.getElementById('customers').innerHTML = '<b>Failed to load data. Check console log</b>';
};
var reloadData = function () {
keycloak.updateToken(10)
.success(loadData)
.error(function() {
document.getElementById('customers').innerHTML = '<b>Failed to load data. User is logged out.</b>';
});
}
答案 0 :(得分:0)
我知道已经很晚了,但是这个答案仅供以后参考。
不知道它是否只是新的,并且此处理程序未在2017年实现,但我使用keycloak.onTokenExpired
来做到这一点。
仅举一个例子:
keycloak.onTokenExpired = () => {
console.log('token expired', keycloak.token);
keycloak.updateToken(30).success(() => {
console.log('successfully get a new token', keycloak.token);
...
}).error(() => {...});
}
答案 1 :(得分:0)