From 3025d69c55ca193eef069419fa26ad8e0fc5aa5d Mon Sep 17 00:00:00 2001 From: Jeffrey Linwood Date: Fri, 12 Jun 2020 07:31:11 -0500 Subject: [PATCH] Refresh access token when it is expired or about to expire --- static/chat/index.js | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/static/chat/index.js b/static/chat/index.js index da1a816..82acaa9 100755 --- a/static/chat/index.js +++ b/static/chat/index.js @@ -41,11 +41,7 @@ $(function() { print('Logging in...'); // 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 - // value "browser" - $.getJSON('/token', { - device: 'browser' - }, function(data) { + $.getJSON('/token', function(data) { // Initialize the Chat client @@ -54,6 +50,16 @@ $(function() { chatClient = client; 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 username = data.identity; 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() { // Get the general chat channel, which is where all the messages are // sent in this simple application