Genesys Cloud - Developer Community!

 View Only

Sign Up

Expand all | Collapse all

Authenticated Web Messaging - JavaScript SDK & Genesys JWT

  • 1.  Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-06-2025 09:34

    Hi Team,

    I am reaching out to the community for feedback on the following:

    Summary:

    According to the official Genesys documentation:

    "Unless revoked, the JWT is valid for 15 minutes (or the access token age, whichever is the smallest) and the refresh token is valid for 24 hours."

    Therefore, in my Genesys Cloud Authenticated Web Messaging deployment, the Identity Provider (IdP) issues an access token with a 5-minute lifetime and a refresh token valid for 30 days. Regardless, Genesys Cloud generates its own tokens as follows:

    • Genesys JWT: 5-minute lifetime
    • Genesys Refresh Token: 24-hour lifetime

    This means the SDK is expected to refresh the Genesys JWT every 5 minutes using the refresh token to maintain an authenticated session.

    Problem:

    Five minutes after successfully authenticating with the Genesys Cloud Web Messenger, the Genesys JWT expires. Assuming the SDK automatically renews the JWT using the refresh token, I would expect that refreshing the brand's web page or opening it in a new browser tab would preserve the authenticated session.

    However, what I am observing instead is that the "Re-authenticate" pop-up appears in the Messenger widget, and the session becomes unresponsive.

    I have been able to resolve the issue by capturing the Genesys JWT and using a JavaScript function to refresh it 100 milliseconds before it expires:

    function scheduleRefresh(jwt) {
        
        const payload = JSON.parse(atob(jwt.split('.')[1]));
        const expiry = payload.exp * 1000;
        const now = Date.now();
        const refreshBefore = 0.1 * 1000; // Refresh JWT 100ms before expiry
        const delay = expiry - now - refreshBefore;
        const timeUntilExpiry = Math.floor((expiry - now)/1000);
    
        console.log("GC JWT expires in", timeUntilExpiry, "seconds");
    
        if (delay > 0) {
            setTimeout(() => {
                Genesys('command', "Auth.refreshToken", {},
                    function() {console.log("GC Messenger JWT has been refreshed");},
                    function() {console.log("GC Messenger JWT refresh failed!");}
                );
            }, delay);
        }
    }

    However, this is not an ideal solution. I would prefer that the SDK handles this automatically as part of its session management.

    I would appreciate your thoughts and any input you may have on this.

    Thanks.


    #PlatformSDK
    #WebMessaging

    ------------------------------
    Arash Fattahi
    ------------------------------


  • 2.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-13-2025 08:31

    Hi Developer Community,

    I would really appreciate any guidance, suggestions, or shared experiences that could help me troubleshoot and resolve the above issue.

    Thanks.



    ------------------------------
    Arash Fattahi
    ------------------------------



  • 3.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-15-2025 20:53

    Hi Arash.

    The only idea I have is increasing the IDP's access token's lifespan. E.g. I believe that 60 minutes is commonly used for access tokens, so is there any reason why you are using one as short as 5 minutes?

    Nick.



    ------------------------------
    Nick Tait
    Genesys Consultant
    ------------------------------



  • 4.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-15-2025 22:20

    Hi @Nick Tait,

    Thanks for your reply.

    The question is not about why we're using a 5-minute lifetime for the access token - this aligns with common security best practices for short-lived tokens.

    The current issue is that the Messenger JavaScript SDK does not automatically refresh the access token internally, contrary to what has been stated by Genesys.

    Thanks.

    Regards,



    ------------------------------
    Arash Fattahi
    ------------------------------



  • 5.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-16-2025 03:23

    Hi Arash, 

    AFAIK you should use the reAuthenticate function . You mentionned this term in your original message but I am not sure you are using this function 

    more details on the auth plugin can be found here https://developer.genesys.cloud/commdigital/digital/webmessaging/messengersdk/SDKCommandsEvents/authProviderPlugin#authprovider-reauthenticate 

    There is also this blueprint app https://developer.genesys.cloud/blueprints/messenger-authentication-okta-integration-blueprint/ 

    regards



    ------------------------------
    Frederic Thomas
    Senior Manager, Development
    ------------------------------



  • 6.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-16-2025 05:10

    Hi @Frederic Thomas,

    Thanks for your reply.

    According to the Genesy documentation:

    When web messaging authentication is enabled and current refreshToken and/or authCode are no more valid, user can re-login with this command. Login action will be triggered on Auth.reAuthenticate to receive new authCode and/or refreshToken.

    However, in my scenario, the refresh token is valid, and I am able to manually refresh the JWT using the following Genesys SDK command:

    Genesys("subscribe", "Auth.ready", function() {
        console.log("GC Auth plugin is ready.");
        Genesys('command', "Auth.refreshToken", {},
            function() {console.log("GC Messenger JWT has been refreshed");},
            function() {
                console.log("GC Messenger JWT refresh failed!");
                Genesys('command', "Auth.reAuthenticate");
            }
        );                    
    });

    The issue I am trying to resolve is why the Messenger SDK does not automatically refresh the JWT?!

    My intention is not to refresh the JWT manually or enforce the re-authentication, but to understand why the automatic refresh mechanism isn't working as expected.

    Thanks.



    ------------------------------
    Arash Fattahi
    ------------------------------



  • 7.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-16-2025 12:24

    Hi @Arash Fattahi

    You don't need to do all this. If your refreshToken is valid, Messenger will automatically get new JWT.

    Couple of questions:

    1. Are you using Headless Messenger SDK with your own UI or using our native Messenger UI?
    2. Do you have `Allow end-users to upgrade an anonymous session to authenticated conversation.` enabled in your Messenger configuration?
    3. Do you have all the needed AuthProvider commands written as documented here, including AuthProvider.reAuthenticate command?

    When the current authCode or refresh token is expired, Messenger will automatically call your `AuthProvider.reAuthenticate` command which will trigger your login process to get new one. Please make sure to have your login process trigger in this command.

    See sample code - https://developer.genesys.cloud/commdigital/digital/webmessaging/messengersdk/authenticatedMessenger

    Blueprint code - https://github.com/GenesysCloudBlueprints/messenger-authentication-okta-integration-blueprint/blob/main/docs/oauth.html

    Thanks,

    Ranjith Sai



    ------------------------------
    Ranjith Manikante Sai
    Senior Manager, Development
    ------------------------------



  • 8.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-16-2025 18:53
    Edited by Arash Fattahi 06-16-2025 18:53

    Hi @Ranjith Manikante Sai,

    Thanks for your reply.

    1. No. We use native Messenger UI.
    2. Yes.
    3. I believe I do. I have included my JavaScript code below.

    With our Identity Provider (IdP), the access token and refresh token lifetimes are configured as follows:

    • Access Token Lifetime: 60 minutes
    • Refresh Token Maximum Lifetime: 30 days

    As a result, and according to the Genesys, the effective lifetimes of the tokens generated by Genesys Cloud will be as follows:

    • JWT (Access Token) Lifetime: 15 minutes
    • Refresh Token Maximum Lifetime: 24 hours

    Thanks.

    console.log("GC Starting Authentication Process ...");
    
    function generateCodeVerifier() {
        const array = new Uint8Array(64);
        crypto.getRandomValues(array);
        return btoa(String.fromCharCode(...array)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    }
    
    async function generateCodeChallenge(codeVerifier) {
        const data = new TextEncoder().encode(codeVerifier);
        const digest = await crypto.subtle.digest("SHA-256", data);
        return btoa(String.fromCharCode(...new Uint8Array(digest))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    }
    
    (async () => {
    
        let currentURL = window.location.origin + window.location.pathname;
        console.log("GC Redirect URL: ", currentURL);
    
        const authUrl = new URL("authEndpointURL");
        authUrl.searchParams.set("response_type", "code");
        authUrl.searchParams.set("response_mode", "query");
        authUrl.searchParams.set("client_id", "clientId");
        authUrl.searchParams.set("redirect_uri", currentURL);
        authUrl.searchParams.set("scope", "openid");
        authUrl.searchParams.set("code_challenge", codeChallenge );
        authUrl.searchParams.set("code_challenge_method", "S256");
        let AuthorizationURL = decodeURIComponent(authUrl.toString());
        console.log("GC Authorisation URL: ", AuthorizationURL);
    
        let authCode;
        let urlParams;
        urlParams = new URLSearchParams(window.location.search);
        authCode = urlParams.get("code");
        console.log('GC Authorisation Code: ', authCode);
    
        let authData = {
            authCode: authCode,
            redirectUri: currentURL,
            codeVerifier: localStorage.getItem('gc_codeVerifier'),
        };
    
        Genesys('registerPlugin', 'AuthProvider', (AuthProvider) => {
    
            AuthProvider.registerCommand('signIn', (e) => {
    
                console.log("GC signIn command received.");
    
                if (authCode) {
    
                    AuthProvider.registerCommand('getAuthCode', (e) => {
                        console.log("GC getAuthCode called.");
                        e.resolve(authData);
                    });                
    
                    e.resolve(authData);
    
                    console.log("GC Publishing signedIn event.");
                    AuthProvider.publish('signedIn', authData);
    
                    const originalPath = window.location.pathname;
                    history.replaceState(null, '', originalPath);
    
                } else {
                    console.log("GC no authCode is available.");
                }
                
            });
    
            AuthProvider.registerCommand('reAuthenticate', (e) => {
                console.log("GC reAuthenticate command received.");
                e.resolve();
            });
    
            AuthProvider.registerCommand('Auth.refreshToken', () => {
                console.log("GC Auth.refreshToken command received.");
            });
    
            AuthProvider.subscribe('Auth.signedIn', (data) => {
                console.log("GC Messenger Auth.signedIn.",data);
            });
    
            AuthProvider.subscribe('Auth.signInFailed', (data) => {
                console.log("GC Messenger Auth.signInFailed.",data);
            });
    
            AuthProvider.subscribe('Auth.authenticated', (data) => {
                console.log("GC Messenger is authenticated",data);
            });
    
            AuthProvider.subscribe('Auth.error', () => {
                console.log("GC Messenger Auth.error.");
                AuthProvider.publish('signInFailed');
            });
    
            AuthProvider.subscribe('Auth.loggedOut', () => {
                console.log("GC Messenger is loggedOut.");
            });
    
            AuthProvider.subscribe('Auth.logoutError', () => {
                console.log("GC Messenger Auth.logoutError.");
            });
    
            AuthProvider.subscribe('Auth.signInAvailable', () => {
                console.log("GC Messenger signInAvailable.");
            });
    
            AuthProvider.subscribe('Auth.signingIn', () => {
                console.log("GC Messenger is signingIn.");
                window.location.href = AuthorizationURL;
            });
    
            AuthProvider.subscribe('Auth.tokenError', () => {
                console.log("GC Messenger Auth.tokenError.");
            });
    
            AuthProvider.subscribe('Auth.authError', () => {
                console.log("GC Messenger Auth.authError.");
                AuthProvider.publish('signInFailed');
            });
    
            AuthProvider.subscribe('Auth.authenticating', () => {
                console.log("GC Messenger is Auth.authenticating.");
            });
    
            AuthProvider.subscribe('Auth.authProviderError', () => {
                console.log("GC Messenger is Auth.authProviderError.");
                AuthProvider.publish('signInFailed');
            });
    
            console.log("GC AuthProvider ready.");
            AuthProvider.ready();
    
        });
    
        if (authCode) {
            Genesys('command', "AuthProvider.Signin");
        }
    })();



    ------------------------------
    Arash Fattahi
    ------------------------------



  • 9.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-17-2025 01:22

    Hi @Arash Fattahi,

    Appreciate sharing the code. Looking at it, I'm seeing couple of things are incorrect.

    1. In your `AuthProvider.registerCommand('signIn')` command, under the else condition you must publish `AuthProvider.signInFailed` event. See documentation related to that here
      } else {
             console.log("GC no authCode is available.");
             AuthProvider.publish('signInFailed', <your auth error data>);
        }
    2. Your `AuthProvider.reAuthenticate` command, is not doing anything. It is simply resolving which is incorrect. It MUST call your login function, typically the one that you use when you hit the login button. See documentation for that here. Refer to the sample blueprint code here.
      AuthProvider.registerCommand('reAuthenticate', (e) => {
      	// This command will be called when current refreshToken and/or authCode are no more valid. User needs to re-login here to provide us new authCode and/or refreshToken.
      	ndAuthLoginBtn.click(); // simulate the login click.
      	e.resolve();
      });
    3. Please remove the below code that is incorrect. What it is doing is registering a command `Auth.refreshToken` that is not asked in our documentation. 
      AuthProvider.registerCommand('Auth.refreshToken', () => {
                  console.log("GC Auth.refreshToken command received.");
              });

    Hopefully these should resolve for you. If not, suggest to reach out to our care team who can assist further in setting this up for you.

    Thanks,

    Ranjith Sai



    ------------------------------
    Ranjith Manikante Sai
    Senior Manager, Development
    ------------------------------



  • 10.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-17-2025 07:29
    Edited by Arash Fattahi 06-17-2025 07:33

    Hi @Ranjith Manikante Sai,

    Thanks for your reply.

    I have updated my JavaScript code based on your recommendation, but unfortunately, it didn't resolve the issue. The Messenger SDK still does not automatically refresh the JWT.

    Please find below the screenshot I captured from my browser's console logs:

    • Yellow Section: Opened my website for the very first time.
    • Blue Section: Clicked the "Sign in" button on the Messenger and completed the authentication process.
    • Red Section: The IdP redirected me back to the web page, the JavaScript code executed, and the Authenticated event appeared to trigger successfully. However, immediately afterward, the reAuthenticate command was triggered, initiating a second authentication process. What I expected was for the Messenger SDK to automatically refresh the JWT.
    • Green Section: Same as the Yellow and Blue sections. The only difference was that I did not need to enter my credentials, and the authentication process was noticeably quicker. 

    I have also shared my JavaScript code for your reference. 

    Please note that the AuthProvider.publish('signInFailed') command is not required, as the second "Sign in" event is automatically triggered when the authCode is present.

    Thanks.

    console.log("GC Starting Authentication Process ...");
    
    let gc_jwt;
    
    let currentURL = window.location.origin + window.location.pathname;
    
    const authUrl = new URL("authEndpointURL");
    authUrl.searchParams.set("response_type", "code");
    authUrl.searchParams.set("response_mode", "query");
    authUrl.searchParams.set("client_id", "clientId");
    authUrl.searchParams.set("audience", "genesys");
    authUrl.searchParams.set("redirect_uri", currentURL);
    authUrl.searchParams.set("scope", "openid offline_access");
    let AuthorizationURL = decodeURIComponent(authUrl.toString());
    
    let authCode;
    let urlParams;
    urlParams = new URLSearchParams(window.location.search);
    authCode = urlParams.get("code");
    
    let authData = {
        authCode: authCode,
        redirectUri: currentURL,
    };
    
    Genesys('registerPlugin', 'AuthProvider', (AuthProvider) => {
    
        AuthProvider.registerCommand('signIn', (e) => {
    
            console.log("GC signIn command received.");
    
            if (authCode) {
    
                AuthProvider.registerCommand('getAuthCode', (e) => {
                    console.log("GC getAuthCode called.");
                    e.resolve(authData);
                });                
    
                e.resolve(authData);
    
                AuthProvider.publish('signedIn', authData);
    
                const originalPath = window.location.pathname;
                history.replaceState(null, '', originalPath);
    
            } else {
                console.log("GC no authCode is available.");
                window.location.href = AuthorizationURL;
            }
            
        });
    
        AuthProvider.registerCommand('reAuthenticate', (e) => {
            console.log("GC reAuthenticate command received.");
            window.location.href = AuthorizationURL;
            e.resolve();
        });
    
        AuthProvider.subscribe('Auth.signedIn', () => {
            console.log("GC Messenger Auth.signedIn.");
        });
    
        AuthProvider.subscribe('Auth.signInFailed', () => {
            console.log("GC Messenger Auth.signInFailed.");
        });
    
        AuthProvider.subscribe('Auth.authenticated', () => {
            console.log("GC Messenger is authenticated");
        });
    
        AuthProvider.subscribe('Auth.error', () => {
            console.log("GC Messenger Auth.error.");
            AuthProvider.publish('signInFailed');
        });
    
        AuthProvider.subscribe('Auth.loggedOut', () => {
            console.log("GC Messenger is loggedOut.");
        });
    
        AuthProvider.subscribe('Auth.logoutError', () => {
            console.log("GC Messenger Auth.logoutError.");
        });
    
        AuthProvider.subscribe('Auth.signInAvailable', () => {
            console.log("GC Messenger signInAvailable.");
        });
    
        AuthProvider.subscribe('Auth.signingIn', () => {
            console.log("GC Messenger is signingIn.");
            window.location.href = AuthorizationURL;
        });
    
        AuthProvider.subscribe('Auth.tokenError', () => {
            console.log("GC Messenger Auth.tokenError.");
        });
    
        AuthProvider.subscribe('Auth.authError', () => {
            console.log("GC Messenger Auth.authError.");
            AuthProvider.publish('signInFailed');
        });
    
        AuthProvider.subscribe('Auth.authenticating', () => {
            console.log("GC Messenger is Auth.authenticating.");
        });
    
        AuthProvider.subscribe('Auth.authProviderError', () => {
            console.log("GC Messenger is Auth.authProviderError.");
            AuthProvider.publish('signInFailed');
        });
    
        console.log("GC AuthProvider ready.");
        AuthProvider.ready();
    
    });
    
    if (authCode) {
        Genesys('command', "AuthProvider.Signin");
    }



    ------------------------------
    Arash Fattahi
    ------------------------------



  • 11.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-24-2025 13:46

    Hi @Arash Fattahi,

    Couple of things from your code:

    1. signIn command is resolving with `e.resolve(authData)` in 2 places. A command should resolve only once.
    2. signIn command should not contain another command inside it. In this case, `getAuthCode` command must be defined outside so Messenger can call it.
    3. I see both signIn and getAuthCode are blended together, that is incorrect. Each command is meant to operate separately. In signIn command, you must have the code that calls your login method i.e., reads where your read user credentials and login. Messenger will call this command when you ask Messenger to upgrade the conversation. If this command is resolved with authCode, that will be used skipping calling getAuthCode command. Otherwise, it will call getAuthCode command after this command is resolved.
    4. Difference between "getAuthCode" and "signIn" command is that, getAuthCode requires user must already logged-in where as signIn knows user is not logged-in and asks to login.
    5. signIn command should publish events "signedIn" or "signInFailed". Instead I see subscription to `Auth.error` event and publishing that as `signInFailed` which is incorrect. Messenger reacts to based on this, reinitializes and updates its UI state.
    6. Inside `Auth.signingIn` event, there is redirection happening with `window.location.href = AuthorizationURL` while sign-in is in-progress, which can lead to issues you are seeing.

    These are some, in-general I suggest to reach out to PS team who can help you better in setting up all these.

    Note: If brand's page reload happens after login, then getAuthCode command will automatically be called (existing mechanism)



    ------------------------------
    Ranjith Manikante Sai
    Senior Manager, Development
    ------------------------------



  • 12.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-20-2025 03:37

    Hi,

    Let me clarify the roles of Genesys Token.
    The JWT provided by Genesys is aimed for authorizing the caller to perform an action on the Genesys protected Apis.
    That is why the lifetime is short (few minutes).
    Example of protected resources: logout, configuring Webmessaging session, etc

    Once the operation is done, and if no further interaction with a protected resource is required, there is no need to get a new JWT.
    The session lifetime is not linked to the JWT but is linked to the Genesys refresh token (so 24 hours max).
    I would even say you should not refresh the JWT if you don't need to use it. Only if you know you're about to call a protected resource.
    This should be a "last in time" strategy.

    As long as the Genesys refresh token is valid, the Webmessaging session remains accessible to the client on resources that do not require a token.

    Hope this helps,

    Regards,
    V.P.



    ------------------------------
    Regards,

    V.P.
    ------------------------------



  • 13.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-22-2025 08:53

    Hi @Vincent Pirat,

    Thank you for the clarification regarding the roles of the Genesys JWT and refresh token.

    Based on your explanation, I understand that the session should remain accessible for up to 24 hours (the maximum supported refresh token lifetime), provided the refresh token remains valid, and that the JWT only needs to be refreshed when accessing protected resources.

    Does this behavior also apply when the user refreshes the page, navigates to a different page, or opens the site in a new browser tab? If so, it appears that the Web Messaging SDK may not be persisting or re-establishing the session using the refresh token as expected.

    I appreciate your guidance on this.

    Thanks.

    Regards,

    Arash Fattahi



    ------------------------------
    Arash Fattahi
    ------------------------------



  • 14.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-24-2025 08:23

    Hi,

    Yes, your statement is correct. Session availability is not linked to UI as long as you keep the same websocket opened once session is established;

    So UI has still some impact on how the web socket is managed. This might vary between various browsers and various mobile clients as well.
    If reloading the UI or navigating away implies closing the websocket, then a valid JWT is required to connect to the (new) websocket and restore the user context when the customer comes back on the page.
    Once session is established, you're done and no further auth flow is required..

    Hope this helps,



    ------------------------------
    Regards,

    V.P.
    ------------------------------



  • 15.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 06-30-2025 00:36

    Hi @Vincent Pirat,

    Thanks for your reply.

    Based on your previous response, it appears that the Genesys Messenger JavaScript SDK does not automatically refresh the JWT. Can you please confirm if this is correct?

    Thanks.

    Regards,

    Arash Fattahi



    ------------------------------
    Arash Fattahi
    ------------------------------



  • 16.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 07-01-2025 12:36

    That is our issue, the socket needs to be reestablished and I am trying to figure out inside the SDK, how to reestablish that socket.

    Do you have an example of how to make this happen?



    ------------------------------
    James Sanders
    Principal Infrastructure Design Engineer
    ------------------------------



  • 17.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 07-03-2025 08:41

    Hi,

    Which SDK are you using ? There are several out there.
    I would expect the SDK to handle the reconnection automatically.
    This might not be instantly but with some delays to avoid network flooding.
    Be aware also that a websocket connection will never exceed 2 hours.
    Unfortunately, I'm not involved on SDK side, so can't help really here.
    If you think there's an issue, I would encourage you to open a ticket with care with as much details as possible on how to reproduce the issue and associated logs.

    Hope this helps



    ------------------------------
    Regards,

    V.P.
    ------------------------------



  • 18.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 07-03-2025 09:19

    JavaScript SDK to reestablish the session. For us, we leave our site for about 30 minutes while a user choosing a doctor and then it redirects back to our site, through session management, we know who the user is and they are still valid but now, the messenger requires reauth, We need to pass the new JWT back into Genesys Messenger.

    How can we send the JWT and revive the session (JavaScript SDK)?



    ------------------------------
    James Sanders
    Principal Infrastructure Design Engineer
    ------------------------------



  • 19.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 07-07-2025 12:11

    Hi James, 

    you should reuse the reauthenticate function and provide the JWT / Refresh Token you get on the first auth call in the SDK

    https://developer.genesys.cloud/commdigital/digital/webmessaging/messengersdk/SDKCommandsEvents/authProviderPlugin#authprovider-reauthenticate 

    https://developer.genesys.cloud/commdigital/digital/webmessaging/messengersdk/authenticatedMessenger



    ------------------------------
    Frederic Thomas
    Senior Manager, Development
    ------------------------------



  • 20.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 07-07-2025 13:03

    So if I understand correctly, I have a valid refreshToken. I can exchange it for a valid JWT (which I can already do).

    To use that valid JWT I simply pass the JWT to the Auth.reAuthenticate?

    Would the resolve look like this?

    { "jwt": "whatever.jwtThatIsValid" }

    Or, are you stating that I can pass the refreshToken as follows:

    {

     "refreshToken": "validNonExpiredRefreshToken",

    "deploymentId": "deploymentForMessenger"

    }

    Thanks,

    James Sanders



    ------------------------------
    James Sanders
    Principal Infrastructure Design Engineer
    ------------------------------



  • 21.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 10-20-2025 21:36

    Hi All, 
    I wanted to check if the issue was resolved? If so, what was the solution? 

    We are experiencing a similar issue

    We are using the built-in messenger that Genesys providers
    Our Messenger Deployment is configured to allow users to upgrade from anonymous sessions
    We are using Azure B2C for our custom brand sign in flow.
     
    From what we gather JWT tokens are limited to 15 minutes (as per Genesys documentation) but could be less due to unforeseen circumstances (e.g. websocket closing). We're using Azure B2C for the login flow without redirecting a user. This process is handled through a modal that embeds an iframe for the login. Azure B2C Auth Code Lifetime: 10 minutes (fixed, non-configurable).
     
    Our current flow is as follow:
    1. Initial authentication succeeds and JWT token is issued.
    2. After 15 minutes the JWT token expires.
    3. Genesys triggers the reAuthenticate command.
    4. We display the sign-in modal and the user completes the Azure B2C login flow.
    5. A new authCode is generated by Azure B2C and given to signInResult function.
    6. We call the resolve() function for the reAuthenticate command with the new auth code (including the redirectUri, codeVerifier).
     
    This is where the problem starts. The resolve appears to have no effect - Genesys logs show "Auth subscribed to ready" but no further authentication progress. The "Re-authenticating..." alert remains displayed indefinitely.
     
    When inspecting browser network traffic, we also observed the Genesys `jwtExchange` API being called to exchange the Azure AuthCode for a JWT token + refresh token. However, it's unclear whether we are expected to handle refresh token logic ourselves or why the session expires despise a refresh token being available. I can only think of it being that we were meant to handle the 'refresh' token ourselves. The documentation is not making this very clear.
     
    My questions are:
     
    1. Why does the `reAuthenticate` resolve fail (do nothing) causing the whole loop to be broken?
    2. Should we handle refresh tokens ourselves, and if so, we're can we find documentation showcasing this for using the built-in messenger?



    Any info will be great!! 

    Thank you



    ------------------------------
    Tony Nguyen
    Smartgroup
    ------------------------------



  • 22.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 17 days ago

    Hi Tony,

    We are experiencing the same issues which you are describing.  We have a `reAuthenticate` function which resolves the same data as the `getAuthCode` function, but the SDK does nothing.  We also (like the original poster above) observe we have to refresh the tokens ourselves, too.

    I would be very interested to hear a response from a Genesys engineer on this topic.  Sounds like many people are experiencing the same thing.

    Alternatively, does Genesys publish the Messenger SDK code as open source?  I wasn't able to find it after a brief search, but it would be nice to see... :-)



    ------------------------------
    Matthew Pfluger
    ------------------------------



  • 23.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 16 days ago

    We are experiencing issues but not at initial authentication, which works fine, but at first refresh, which is when the Genesys code goes into an endless loop.

    Regards



    ------------------------------
    Vineet Kakroo
    Senior Technical Consultant
    ------------------------------



  • 24.  RE: Authenticated Web Messaging - JavaScript SDK & Genesys JWT

    Posted 16 days ago

    Hi Tony,

    If you attempt to refresh the token while it's still valid, Genesys won't issue a new one.

    To handle this properly, your code should include logic to track the token's lifetime and trigger a manual refresh a few milliseconds before it expires. This ensures a new token is generated and a reauthentication event is triggered. Something like the following:

    console.log("GC Starting Authentication Process ...");
    
    function scheduleRefresh(jwt) {
        
        const payload = JSON.parse(atob(jwt.split('.')[1]));
        const expiry = payload.exp * 1000;
        const now = Date.now();
        const refreshBefore = 0.000001 * 1000; // Refresh 0.001s before expiry
        const delay = expiry - now - refreshBefore;
        const timeUntilExpiry = Math.floor((expiry - now)/1000);
    
        console.log("GC JWT expires in", timeUntilExpiry, "seconds");
    
        if (delay > 0) {
            setTimeout(() => {
                Genesys('command', "Auth.refreshToken", {},
                    function() {console.log("GC Messenger JWT has been refreshed");},
                    function() {console.log("GC Messenger JWT refresh failed!");}
                );
            }, delay);
        }
    }

    The call the above function under the "Auth.authenticated" event:

    AuthProvider.subscribe('Auth.authenticated', (data) => {
        gc_jwt = data.data.jwt;
        console.log("GC Messenger is authenticated.",data);
        console.log("GC Messenger JWT is: ", gc_jwt);
        scheduleRefresh(gc_jwt);
    });

    Also, I raised an idea with Genesys for "Automatically Refresh Genesys Cloud JWT Token", and the good news is that it's currently under development.

    Hope this helps.

    Thanks.



    ------------------------------
    Arash Fattahi
    ------------------------------