Parsing an access token (JWT Token) using TypeScript

Posted on 5/29/2016 @ 3:16 AM in #Vanilla .NET by | Feedback | 3325 views

Here is a helpful piece of code. As the name suggests, it is a simple class that lets you decrypt an access token. And it’s in TypeScript so its easy to use in Angular2 etc.

   1:  export class JwtHelper {
   2:      private urlBase64Decode(str: string) {
   3:          var output = str.replace(/-/g, '+').replace(/_/g, '/');
   4:          switch (output.length % 4) {
   5:              case 0: { break; }
   6:              case 2: { output += '=='; break; }
   7:              case 3: { output += '='; break; }
   8:              default: {
   9:                  throw 'Illegal base64url string!';
  10:              }
  11:          }
  12:          return decodeURIComponent(escape(window.atob(output)));
  13:      }
  14:   
  15:      public decodeToken(token: string) {
  16:          var parts = token.split('.');
  17:          if (parts.length !== 3) {
  18:              throw new Error('JWT must have 3 parts');
  19:          }
  20:          var decoded = this.urlBase64Decode(parts[1]);
  21:          if (!decoded) {
  22:              throw new Error('Cannot decode the token');
  23:          }
  24:          return JSON.parse(decoded);
  25:      }
  26:  }

So how do you use it? Easy!

   1:  import {JwtHelper} from './JwtHelper';
   2:  export class SomeClass{
   3:     // other logic goes here..
   4:      public get userName() {
   5:          var jwtHelper = new JwtHelper();
   6:          var parsedToken = jwtHelper.decodeToken("str_access_token");
   7:          return parsedToken.upn;
   8:      }
   9:  }

Have fun!

Sound off but keep it civil:

Older comments..