Learn the powerful enterprise adaptable database:

Getting Started With ADABAS & Natural

Monday, April 24, 2017

Apps Script and JSON Web Token




Introduction

This tutorial demonstrates the use of JSON Web Token in Apps Script.

Objective

1. Add JWT Library.
2. Encode token.

3. Decode token.


1.Add JWT Library

We can add JWT in two ways:

1. Link to the external site.

eval(UrlFetchApp.fetch('https://kjur.github.io/jsrsasign/jsrsasign-latest-all-min.js').getContentText());


2. Get the codes from the source and paste into code file.

You may get the following error during run time:

navigator is not defined

window is not defined

Solution: Add the following codes to declare them
var navigator = {};  
var window = {};  

2.Sample codes


var navigator = {};  
var window = {};  
//eval(UrlFetchApp.fetch('https://kjur.github.io/jsrsasign/jsrsasign-latest-all-min.js').getContentText());
/* sample output:
Signing JSON Web Token:eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjogInVzZXIiLCJnbWFpbCI6InVzZXJAZ21haWwuY29tIn0.iM_n__aH7Bl1ZfJirgTckU51x1xbRi6cw8lJMK4G5K8
Validate Signature:true
*** Header ***
Parsing Header:{"alg":"HS256"}
*** Payload ***
Parsing Payload:{"name":"user","gmail":"user@gmail.com"}
*/


function myfunction(){

  // JWS signing 
sJWT = KJUR.jws.JWS.sign(null, '{"alg":"HS256"}', '{"name": "user","gmail":"user@gmail.com"}', {"utf8": "password"});

Logger.log("Signing JSON Web Token:"+sJWT);

// JWT validation
isValid = KJUR.jws.JWS.verifyJWT(sJWT, {"utf8": "password"}, {alg: ["HS256"]});
Logger.log("Validate Signature:"+isValid);

var headerObj = KJUR.jws.JWS.readSafeJSONString(b64utoutf8(sJWT.split(".")[0]));
Logger.log("*** Header ***");
Logger.log("Parsing Header:"+JSON.stringify(headerObj));

var payloadObj = KJUR.jws.JWS.readSafeJSONString(b64utoutf8(sJWT.split(".")[1]));
Logger.log("*** Payload ***");
Logger.log("Parsing Payload:"+JSON.stringify(payloadObj));

}

3.References

1. https://www.jonathan-petitcolas.com/2014/11/27/creating-json-web-token-in-javascript.html
2. https://codepen.io/jpetitcolas/pen/zxGxKN
3. https://jwt.io/
4. https://community.servicenow.com/thread/208145
5. https://kjur.github.io/jsrsasign/api/symbols/KJUR.jws.JWS.html
6. https://community.apigee.com/questions/28794/best-practices-for-passing-an-access-token-without.html
7. https://auth0.com/blog/angularjs-authentication-with-cookies-vs-token/
8. https://stormpath.com/blog/build-secure-user-interfaces-using-jwts
9. https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#checktoken
10. https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage
11. http://googleappscripting.com/doget-dopost-tutorial-examples/


201704, 20170423, JWT, FIREBASE

No comments:

Post a Comment