Refresh access token when it is expired or about to expire

This commit is contained in:
Jeffrey Linwood
2020-06-12 07:31:11 -05:00
parent 845f7959ab
commit 3025d69c55

View File

@@ -41,11 +41,7 @@ $(function() {
print('Logging in...'); print('Logging in...');
// Get an access token for the current user, passing a username (identity) // Get an access token for the current user, passing a username (identity)
// and a device ID - for browser-based apps, we'll always just use the $.getJSON('/token', function(data) {
// value "browser"
$.getJSON('/token', {
device: 'browser'
}, function(data) {
// Initialize the Chat client // Initialize the Chat client
@@ -54,6 +50,16 @@ $(function() {
chatClient = client; chatClient = client;
chatClient.getSubscribedChannels().then(createOrJoinGeneralChannel); chatClient.getSubscribedChannels().then(createOrJoinGeneralChannel);
// when the access token is about to expire, refresh it
chatClient.on('tokenAboutToExpire', function() {
refreshToken(username);
});
// if the access token already expired, refresh it
chatClient.on('tokenExpired', function() {
refreshToken(username);
});
// Alert the user they have been assigned a random username // Alert the user they have been assigned a random username
username = data.identity; username = data.identity;
print('You have been assigned a random username of: ' print('You have been assigned a random username of: '
@@ -66,6 +72,16 @@ $(function() {
}); });
}); });
function refreshToken(identity) {
console.log('Token about to expire');
// Make a secure request to your backend to retrieve a refreshed access token.
// Use an authentication mechanism to prevent token exposure to 3rd parties.
$.getJSON('/token/' + identity, function(data) {
console.log('updated token for chat client');
chatClient.updateToken(data.token);
});
}
function createOrJoinGeneralChannel() { function createOrJoinGeneralChannel() {
// Get the general chat channel, which is where all the messages are // Get the general chat channel, which is where all the messages are
// sent in this simple application // sent in this simple application