Uploaded image for project: 'Keycloak'
  1. Keycloak
  2. KEYCLOAK-14917

Keycloak-js decodeToken fails when token contains underscore (Failed to execute 'atob')

    Details

    • Steps to Reproduce:
      Hide

      decodeToken eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb3JlbSI6Imlwc3VtPz8_In0.bUkJRFKoE18BWYa3idYzZqJhBGeavg86J0PqUjx4i-E

      Show
      decodeToken eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb3JlbSI6Imlwc3VtPz8_In0.bUkJRFKoE18BWYa3idYzZqJhBGeavg86J0PqUjx4i-E
    • Docs QE Status:
      NEW
    • QE Status:
      NEW

      Description

      Tokens containing underscore `_` (and also minus `-`) fail to decode:

      // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb3JlbSI6Imlwc3VtPz8_In0.bUkJRFKoE18BWYa3idYzZqJhBGeavg86J0PqUjx4i-E
      Uncaught DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
      

      The problem comes fromĀ decodeToken

      function decodeToken(str) {
                  str = str.split('.')[1];
      
                  str = str.replace('/-/g', '+');
                  str = str.replace('/_/g', '/');
                  switch (str.length % 4) {
                      case 0:
                          break;
                      case 2:
                          str += '==';
                          break;
                      case 3:
                          str += '=';
                          break;
                      default:
                          throw 'Invalid token';
                  }
      
                  str = decodeURIComponent(escape(atob(str)));
      
                  str = JSON.parse(str);
                  return str;
              }
      

      The line ` str = str.replace('/_/g', '/');` doesn't actually work, it tries to replace the string not the regex ...

      This bug was introduced in 11.0 by KEYCLOAK-13940 which removed a duplicate piece of code that actually did the regex replacement.

        Gliffy Diagrams

          Attachments

            Issue Links

              Activity

                People

                • Assignee:
                  pcraveiro Pedro Igor Silva
                  Reporter:
                  danmana Dan Manastireanu
                • Votes:
                  0 Vote for this issue
                  Watchers:
                  2 Start watching this issue

                  Dates

                  • Created:
                    Updated:
                    Resolved: