Wiki: Tutorial for JWT generation

TOP | static wiki | wiki | DOWNLOADS | TUTORIALS | API REFERENCE | DEMOS |

TOP(jsrsasign) | WIKI | DOWNLOADS | TUTORIALS | API REFERENCE | DEMOS


To use jsrsasign including jsjws on your browser, just include 'jsrsasign-latest-all-min.js' script as following:

<script language="JavaScript" type="text/javascript"
        src="https://kjur.github.io/jsrsasign/jsrsasign-latest-all-min.js">
</script>

JSON Web Token(JWT) generation is very similar to JSON Web Signature(JWS) generation since those difference is just payload. JWS generation is to create header and payload JSON object with necessary claims and then sign it.

Time in JWS/JWT, integer value for UNIX origin time since 1970 Jan 1 will be used. To specify time value KJUR.jws.IntData.get method is very useful.

Here is a sample for a JWT generation with HS256 signature algorithm:

// Header
var oHeader = {alg: 'HS256', typ: 'JWT'};
// Payload
var oPayload = {};
var tNow = KJUR.jws.IntDate.get('now');
var tEnd = KJUR.jws.IntDate.get('now + 1day');
oPayload.iss = "http://foo.com";
oPayload.sub = "mailto:mike@foo.com";
oPayload.nbf = tNow;
oPayload.iat = tNow;
oPayload.exp = tEnd;
oPayload.jti = "id123456";
oPayload.aud = "http://foo.com/employee";
// Sign JWT, password=616161
var sHeader = JSON.stringify(oHeader);
var sPayload = JSON.stringify(oPayload);
var sJWT = KJUR.jws.JWS.sign("HS256", sHeader, sPayload, "616161");

When you want to sign JWT by your private key of public key cryptography, KEYUTIL.getKey method can be used to load PKCS#1 or PKCS#8 PEM formatted encrypted or plain private key. Here is an example:

var prvKey = KEYUTIL.getKey(sPKCS8PEM, "password");
var sJWT = KJUR.jws.JWS.sign("RS256", sHeader, sPayload, prvKey);

Please also see Online JWT generation/verification tool.

jwt.io site interoperability

jwt.io site can generate and verify HS256/384/512 JWT online and it uses old version of jsrsasign. However difference of way to specify password between jwt.io and jsrsasign may make some confusion.

jwt.io

jsrsasign

In order to verify jsrsasign generated HS* JWT by jwt.io site, specify password as one of follows:

var sJWT = KJUR.jws.JWS.sign("HS256", sHeader, sPayload, {rstr: "secret"});
var sJWT = KJUR.jws.JWS.sign("HS256", sHeader, sPayload, {utf8: "secret"});
var sJWT = KJUR.jws.JWS.sign("HS256", sHeader, sPayload, {b64u: "c2VjcmV0"});
var sJWT = KJUR.jws.JWS.sign("HS256", sHeader, sPayload, {b64: "c2VjcmV0"});
var sJWT = KJUR.jws.JWS.sign("HS256", sHeader, sPayload, {hex: "736563726574"});
var sJWT = KJUR.jws.JWS.sign("HS256", sHeader, sPayload, "736563726574");