Jul 12, 2019

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share this details with Client Applications which can be either PHP, HTML JavaScript, Angular, etc...

For This JWT (Jason Web Token) comes in handy as a Token to share with client and server. You can read more about JWT in there Website.

You can use below Jquery code to decode the given JWT Token and access the details in it.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html>
<head>
    <title>JWT Token Decode Using Jquery</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>
<body>
    <h3> JWT Token Decode Using Jquery</h3>
    <form>
       <textarea rows="2" cols="50" id="token"></textarea>
       <br/>
       <input type="button" name="Decode" id="btnDecode" value="Decode">
       <br/>
       <textarea rows="10" cols="50" id="txtDecode"></textarea>
    </form>
 
    <script>
       $(document).ready(function(){
          $("#btnDecode").click(function(event){
             var token = $('#token').val();
             if(token == ""){
                $("#txtDecode").val("Please insert the Token");
             }else{
                var decodedToken = parseJwt(token);
                $("#txtDecode").val(JSON.stringify(decodedToken));
             }
          });
        });
  
        function parseJwt (token) {
           var base64Url = token.split('.')[1];
           var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
           var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
             return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
             }).join(''));

           return JSON.parse(jsonPayload);
        };
  
    </script>
</body>
</html>

I have used the below token to test this code.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJNZW1iZXJJZCI6IjEiLCJNZW1iZXJOYW1lIjoi2YbZitmB2KfZhCDZhtiy2KfYsSIsIk1lbWJlckVtYWlsIjoiYWR2b3F1ZXNAZ21haWwuY29tIiwibmJmIjoxNTYyODU5MDcwLCJleHAiOjE1NjI5MzEwNzAsImlzcyI6IlN1a25hIiwiYXVkIjoiU3VrbmEifQ.A-v4D1u4HE1sKBDiZBTQ79WAkLVNnAcKrURRDkLv7bQ

This how it looks like. Hope you also got it correct.




No comments:

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...