Speed up development with full-stack environments for every branch.

Learn More

Deconstruct a JWT token for Firebase [JavaScript]

327 Runs 1540 Views 362 Copies
Saved

Saved

sundip 66

sundip
published 4 years ago

<html>
  <head>
  
    <!-- Installing Firebase from CDN -->
    <script src='https://cdn.firebase.com/v0/firebase.js'></script>

    <script type="text/javascript">
              
        // Helper function to extract claims from a JWT. Does *not* verify the
        // validity of the token. 
        // credits: https://github.com/firebase/angularFire/blob/master/angularFire.js#L370
        function deconstructJWT(token) {
           var segments = token.split(".");
           if (!segments instanceof Array || segments.length !== 3) {
              throw new Error("Invalid JWT");
           }
           var claims = segments[1];
           return JSON.parse(decodeURIComponent(escape(window.atob(claims))));
        }
        
        // Gets the JWT value from the textarea and calls 'deconstructJWT'
        // to extract claims.
        // Then outputs it for the user to see.
        function go() {
          var jwt = document.getElementById('jwt').value;
          var output = '';
          
          try {
            output = deconstructJWT(jwt);
            output = JSON.stringify(output);
          } catch(e) {
            output = "Invalid JWT";
          }
          
          document.getElementById('output').innerHTML = output;
        }
        
    </script>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <h1>Deconstruct JWT tokens for Firebase</h1>
    
    <!-- JWT default value obtained from 
         https://www.firebase.com/docs/security/custom-login.html -->
    <textarea id="jwt">eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhZG1pbiI6dHJ1ZSwidiI6MCwiaWF0IjoxMzU5OTQzMDY3LCJkIjp7InVzZXIiOiJ0ZXN0In19.iGAOVRoS0EPZG53zpSjrTEvk_kYFSZRw621ixnnSDFY</textarea>
    <button id="go" onclick="go()">Deconstruct JWT</button>
    
    <h2>Output</h2>
    <pre id="output"></pre>
  </body>
</html>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).