Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save visualjeff/dc8edfde6433b1634a989ac39454ecc1 to your computer and use it in GitHub Desktop.
Save visualjeff/dc8edfde6433b1634a989ac39454ecc1 to your computer and use it in GitHub Desktop.
pure Javascript JWT Validation
<!doctype html>
<html class="no-js" lang="en">
<head>
<!-- Written by: jgilber (a.k.a., visualjeff on github) -->
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JWT Token Validator</title>
<script src="https://kjur.github.io/jsrsasign/jsrsasign-latest-all-min.js" crossorigin="anonymous"></script>
</head>
<body>
<script>
const token = '<<ENCODED RAW JWT TOKEN HERE>>';
const iss = ['https://sts.windows.net/<<TENANTID_HERE>>'];
const sub = ['<<SUBJECT_HERE>>']; // Principal (user id in AAD) about which the token asserts information
const aud = ['<<AUDIENCE_HERE>>']; // Could be https://graph.windows.net
const decodeToken = function (token) {
return {
header: KJUR.jws.JWS.readSafeJSONString(b64utoutf8(token.split('.')[0])),
payload: KJUR.jws.JWS.readSafeJSONString(b64utoutf8(token.split('.')[1]))
};
}
//To avoid CORS restriction when running locally. Install the Chrome extension: Allow-Control-Allow-Origin: *
const getSigningCertificate = async function (kid) {
const json = await (await fetch(`https://login.microsoftonline.com/common/discovery/v2.0/keys`)).json();
const match = json.keys.find(key => {
return key.kid === kid;
});
return match.x5c[0];
};
const basicJWTValidation = async function (token, iss, sub, aud, now = KJUR.jws.IntDate.get('now')) {
const { header, payload } = decodeToken(token);
const cert = await getSigningCertificate(header.kid);
const pubkey = KEYUTIL.getKey(`-----BEGIN CERTIFICATE-----\n${cert}\n-----END CERTIFICATE-----`);
return KJUR.jws.JWS.verifyJWT(token, pubkey, {
alg: ['RS256'], iss, sub, verifyAt: now, aud
});
};
basicJWTValidation(token, iss, sub, aud).then(isValid => {
console.log(`isValid: ${isValid}`); //Prints true if valid to the console log
});
</script>
</body>
</html>
@visualjeff
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment