Created
December 2, 2019 22:39
-
-
Save isapir/adeed844fb3e286e6b9846250aa831dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
component { | |
this.algorithms = { | |
"HS256" : "HMACSHA256" | |
}; | |
/** | |
* initializes the object with the secret that is used to sign the JWT | |
*/ | |
function init(secret) { | |
variables.secret = arguments.secret; | |
} | |
function parse(jwt) { | |
var parts = listToArray(arguments.jwt, "."); | |
if (parts.len() != 3) | |
throw("Invalid JWT: expected 3 parts"); | |
try { | |
var header = deserializeJSON(base64UrlDecode(parts[1])); | |
var payload = deserializeJSON(base64UrlDecode(parts[2])); | |
} | |
catch (ex) { | |
throw("Invalid JWT: expected JSON object. #ex.message#"); | |
} | |
var signature = parts[3]; | |
var algo = header.alg ?: ""; | |
if (isEmpty(algo)) | |
throw("Invalid JWT: header.alg is missing") | |
if (this.algorithms.keyExists(algo)) | |
algo = this.algorithms[header.alg]; | |
var hexHmac = hmac(parts[1] & "." & parts[2], variables.secret, algo); | |
var binHmac = binaryDecode(hexHmac, "hex"); | |
var encodedHmac = base64UrlEncode(binHmac); | |
var isSigValid = (encodedHmac == signature); | |
if (!isSigValid) | |
throw("Invalid JWT: invalid signature"); | |
return { | |
header : header | |
,payload : payload | |
,isValid : isSigValid | |
}; | |
} | |
function base64UrlDecode(input) { | |
return toString(toBinary(arguments.input)); | |
} | |
function base64UrlEncode(input) { | |
var result = toBase64(arguments.input); | |
result = listFirst(result, "="); // remove trailing = | |
result = replace(result, "+", "-", "all"); // 62nd char of encoding | |
result = replace(result, "/", "_", "all"); // 63rd char of encoding | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment