-
-
Notifications
You must be signed in to change notification settings - Fork 643
Tutorial for JWT verification
TOP | 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>
The 'jsrsasign' 4.8.0 or later supports validation for JSON Web Token(JWT) by KJUR.jws.JWS.verifyJWT method. To verify it, you need key for signature of JWT and some parameters.
If HMAC is used for JWT signing, you can specify shared key by a hexadecimal string of key. Otherwise, you may need to specify public key. Easiest way is to provide PEM text formatted X.509 public key certificate for JWT signer.
For example, certificate will be shown as following text.
----- BEGIN CERTIFICATE -----
MIIDET....
... snip ... (Base64 encoded certificate)
----- END CERTIFICATE -----
When you have a string for PEM certificate, you can load public key object by following method.
var pubkey = KEYUTIL.getKey(certStr);
You can use the same method to load public key PEM file.
Following code is for simplest HS256 JWT validation and to verify signature, time(i.e. ordering current time with 'exp', 'nbf' and 'iat' claims) existence of 'jti' claim and acceptable algorithm:
var isValid = KJUR.jws.JWS.verifyJWT("eyT...", "616161", {alg: ['HS256']});
If you want to verify JWT at specified time, you can use 'verifyAt' property:
// verify JWT at 1 Jun 2015. HMAC shared key is "616161" (i.e. string "aaa")
var IntDate = KJUR.jws.IntDate;
var isValid = KJUR.jws.JWS.verifyJWT("eyT...", "616161",
{alg: ['HS256'],
verifyAt: IntDate.get('20150601000000Z')});
As for other acceptable claims like 'iss', 'sub' and 'aud', sample fill be following:
var IntDate = KJUR.jws.IntDate;
var isValid = KJUR.jws.JWS.verifyJWT("eyT...", "616161",
{alg: ['HS256'],
verifyAt: IntDate.get('20150601000000Z'),
iss: ['http://foo.com', http://us.foo.com],
sub: ['mailto:mike@foo.com',
'mailto:kate@foo.com'],
aud: ['http://foo.com/employee',
'http://foo.com/partner']});
Finally, to get JSON object of header and payload in the token, there are many ways but here is one:
var sJWT = "eyT...";
var headerObj = KJUR.jws.JWS.readSafeJSONString(b64utoutf8(sJWT.split(".")[0]));
var payloadObj = KJUR.jws.JWS.readSafeJSONString(b64utoutf8(sJWT.split(".")[1]));
Please also see Online JWT verification tool.