Genesys Cloud - Developer Community!

 View Only

Sign Up

  • 1.  PKCE Grant Failing with loginPKCEGrant – Generic [Error] at ApiClient.js Line 814

    Posted 06-02-2025 14:51

    Hi all,

    We're trying to authenticate using the PKCE grant type with the Genesys Cloud JavaScript SDK (platformClient). However, we're hitting a vague error in ApiClient.js at line 814 during the loginPKCEGrant flow. Here's the relevant code in the SDK:

    this.computePKCECodeChallenge(this.codeVerifier)
      .then((codeChallenge) => {
        var tokenQuery = {
          client_id: encodeURIComponent(this.clientId),
          redirect_uri: encodeURIComponent(this.redirectUri),
          code_challenge: encodeURIComponent(codeChallenge),
          response_type: 'code',
          code_challenge_method: 'S256'
        };
        if (opts.state) tokenQuery.state = encodeURIComponent(opts.state);
        if (opts.org) tokenQuery.org = encodeURIComponent(opts.org);
        if (opts.provider) tokenQuery.provider = encodeURIComponent(opts.provider);
    
        var url = this._buildAuthUrl('oauth/authorize', tokenQuery);
        window.location.replace(url);
      })
      .catch((err) => {
        return reject(new Error(`[${err.name}]`)); // line 814
      });
    

    And here's how we're invoking it in our app:

    useEffect(() => {
      const client = platformClient.ApiClient.instance;
      client.setEnvironment('mypurecloud.com');
      client.setPersistSettings(true, 'purecloud');
    
      const clientId = import.meta.env.VITE_PURECLOUD_CLIENT_ID;
      const redirectUri = import.meta.env.VITE_PURECLOUD_REDIRECT_URI;
    
      if (!client.authData?.accessToken) {
        client
          .loginPKCEGrant(clientId, redirectUri)
          .then(() => console.log('Genesys Cloud authenticated'))
          .catch((err) => console.error('Auth error', err));
      }
    }, []);

    The error we receive in the console is just:

    Auth error Error: [Error]
        at ApiClient.js:814:37

    However, when we change the grant type to Implicit Grant on the OAuth client and use loginImplicitGrant, everything works fine. This suggests the client ID and redirect URI are correct, so I'm not sure where the problem could be.

    We need to use PKCE to support auto-refreshing of the access token, so falling back to Implicit Grant isn't a viable long-term solution.

    Has anyone seen this before? Any insight into what could cause computePKCECodeChallenge to fail?

    Thanks in advance!


    #PlatformSDK

    ------------------------------
    Branson Berry
    IT Director
    ------------------------------


  • 2.  RE: PKCE Grant Failing with loginPKCEGrant – Generic [Error] at ApiClient.js Line 814

    Posted 06-03-2025 07:13

    Hi Branson Berry,

    We recommend trying with GC API implementation of PKCE once. Its similar to the SDK implementation but you have move control over the API calls, redirects and data flow. It helps to identify issue point.

    Grant - Proof Key for Code Exchange (PKCE)



    ------------------------------
    Parthiban Thangarajan
    Principal Full Stack Developer
    ------------------------------



  • 3.  RE: PKCE Grant Failing with loginPKCEGrant – Generic [Error] at ApiClient.js Line 814

    Posted 06-03-2025 08:13

    Hello,

    The PKCE Grant with Genesys Cloud does not support refresh token. Only the Authorization Code Grant does.

    John recently proposed an interesting approach to implement a process to get a new token on client side - see here: https://community.genesys.com/discussion/error-you-are-not-authorized-to-perform-the-requested-action#bm9cd67d0d-3a09-4e0c-92bf-019718018c8b

    Regards,



    ------------------------------
    Jerome Saint-Marc
    Senior Development Support Engineer
    ------------------------------



  • 4.  RE: PKCE Grant Failing with loginPKCEGrant – Generic [Error] at ApiClient.js Line 814

    Posted 21 days ago
    Edited by Nick Tait 21 days ago

    I've been having the exact same issue...

    For background, I've been developing Vue.js applications for the last year or so, using purecloud-platform-client-v2 library. So the application uses the NPM library, but executes within the browser (i.e. not Node.js). This has always worked fine when authenticating the user with loginImplicitGrant. However I've never been able to get loginPKCEGrant to work because it always results in the generic "[Error]" described above, which I've discovered is due to a ReferenceError (Buffer is not defined) being thrown on the following line (within computePKCECodeChallenge function):

    					const hashBase64 = Buffer.from(hashBuffer).toString('base64');
    

    In troubleshooting this issue, I've discovered that if your web application loads the CommonJS SDK using the following method, the loginPKCEGrant function works as expected.

    <!-- Include the CJS SDK -->
    <script src="https://sdk-cdn.mypurecloud.com/javascript/234.0.0/purecloud-platform-client-v2.min.js"></script>
    

    So then I started comparing the code in the NPM library with the CommonJS SDK. I discovered the NPM library contains logic to cater for running within Node.js and the browser, whereas the CommonJS SDK just contains the browser code. But in both cases the same statements are executed.

    The crucial difference is that the CommonJS SDK defines its own Buffer function, and so when it executes the line cited above, it doesn't throw an exception. In contrast the Buffer function isn't defined in the NPM version of the library, which I'm assuming is because Node.js provides that function when the application is running within a Node.js environment.

    So I guess this code block (within computePKCECodeChallenge function) needs to be rewritten to not use Buffer.from()?

    			// browser
    			const utf8 = new TextEncoder().encode(code);
    			return new Promise((resolve, reject) => {
    				window.crypto.subtle.digest("SHA-256", utf8).then((hashBuffer) => {
    					const hashBase64 = Buffer.from(hashBuffer).toString('base64');
    					let hashBase64Url = hashBase64.replaceAll("+", "-").replaceAll("/", "_");
    					hashBase64Url = hashBase64Url.split("=")[0];
    					resolve(hashBase64Url);
    				})
    				.catch((error) => {
    					// Handle failure
    					return reject(new Error(`Code Challenge Error ${error}`));
    				});
    			});
    

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



  • 5.  RE: PKCE Grant Failing with loginPKCEGrant – Generic [Error] at ApiClient.js Line 814

    Posted 16 days ago

    I get the feeling that my update was somehow missed out of the digest emails...

    @Parthiban Thangarajan I'd be interested in your assessment of my comment above?



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



  • 6.  RE: PKCE Grant Failing with loginPKCEGrant – Generic [Error] at ApiClient.js Line 814

    Posted 15 days ago

    Hello Nick,

    I have seen your post but I am currently out of office (holidays). I am back mid next week.

    Your post helped me to understand. Thanks for this.

    To explain a bit:

    The "source" for all our javascript SDKs is the nodejs version. It is used to then build the web-cjs and amd versions of the library.

    When building the web-cjs, we inject polyfills to manage methods which are not supported in browser based javascript - like the Buffer.from.

    That's why it works fine when your are using the web-cjs library. And why you are having an issue when using the nodejs version (for a browser client).

    Why it appears now (these last years) and not previsouly:

    I am not a web developper. But from what I have found after you sent your post is that bundlers like webpack and others used to manage and inject these polyfills "by default". In more recent versions (webpack >= 5), they are not doing so anymore. The polyfills need to be explicitly specified in the bundler project.

    For short time, you could try to specify one for buffer package if you can.

    Next:

    If you don't mind, it'd be great if you could create a ticket with support, so we can track this work and the effort. You can reference this post so they open an internal task for the SDK team.

    I have found/coded a piece of code that works with browser based javascript (for the computePKCECodeChallenge).

    What I don't know yet is if it will cause issues with the nodejs library (to be more specific with the nodejs sdk in a typescript project). I need to verify if all the methods are known to node js (even if they do something different than with a browser). As otherwise, this would generate errors (from our node library) when trying to build a typescript node project.

    If it does generate errors, another approach I could take would be to extend the loginPKCEGrant method, allowing to pass both codeVerifier and codeChallenge as input, and document the code for a browser based computeCodeChallenge in the readme (right now, it only supports the codeVerifier as method optional parameter).

    I'll start having a look at this when I am back next week.

    Hope this clarifies.

    Regards,



    ------------------------------
    Jerome Saint-Marc
    Senior Development Support Engineer
    ------------------------------



  • 7.  RE: PKCE Grant Failing with loginPKCEGrant – Generic [Error] at ApiClient.js Line 814

    Posted 15 days ago

    @Jerome Saint-Marc Thanks for your response. I've raised a support case for this issue. Ref=0003908622



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



  • 8.  RE: PKCE Grant Failing with loginPKCEGrant – Generic [Error] at ApiClient.js Line 814

    Posted 15 days ago

    Hi @Nick Tait 

    I've just had to implement PKCE Oauth flow for a client side web app. Similar to @Parthiban Thangarajan I suggest using the GC API directly as you won't have to deal with the error from using `Buffer` . This is a great resource that helped me https://developer.genesys.cloud/blog/oauth-pkce-intro



    ------------------------------
    Ewomazino Onokpise
    Software Engineer
    ------------------------------



  • 9.  RE: PKCE Grant Failing with loginPKCEGrant – Generic [Error] at ApiClient.js Line 814

    Posted 15 days ago

    Thanks for the info. (I don't currently have anyone demanding that we implement PKCE ASAP, so I'd prefer to stick with Implicit grant for now and wait for loginPKCEGrant to be fixed in the SDK rather than implementing 100 lines of Typescript as a workaround!)

    It is interesting to compare the code on the page you provided the link for with the code in the SDK though... It looks like the fix for the SDK could be as simple as replacing the single line:

    const hashBase64 = Buffer.from(hashBuffer).toString('base64');

    with:

    const hashBase64 = btoa(String.fromCharCode(...new Uint8Array(hashBuffer));

    Nick.



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



  • 10.  RE: PKCE Grant Failing with loginPKCEGrant – Generic [Error] at ApiClient.js Line 814

    Posted 7 days ago

    Hello,

    Yes, this is also what I'm planning to use. I just need to check that it doesn't affect the nodejs library (used in a typescript project).

    I will let you know (I'll update this post) once it is done and in the SDK.

    Regards,



    ------------------------------
    Jerome Saint-Marc
    Senior Development Support Engineer
    ------------------------------