Skip to content

Instantly share code, notes, and snippets.

@mikeacjones
Created April 19, 2021 22:37
Show Gist options
  • Save mikeacjones/564a88afd5cf14b460bd16fb139b9b31 to your computer and use it in GitHub Desktop.
Save mikeacjones/564a88afd5cf14b460bd16fb139b9b31 to your computer and use it in GitHub Desktop.
Dataweave JWT Creation
%dw 2.0
import HMACBinary from dw::Crypto
import toBase64 from dw::core::Binaries
fun binaryJson(obj: Object) =
write(obj, 'application/json', { indent: false }) as Binary
fun base64URL(str: Binary) =
toBase64(str) replace "+" with "-" replace "/" with "_" replace "=" with ""
fun base64Obj(obj: Object) =
base64URL(binaryJson(obj))
/** basic JWT with header and payload, no signing */
fun JWT(header: Object, payload: Object) =
"$(base64Obj(header)).$(base64Obj(payload))"
/** basic JWT with no user specified header */
fun JWT(payload: Object) =
JWT({typ:'JWT'}, payload)
fun signJWT(content: String, key: String, alg) =
base64URL(HMACBinary(key as Binary, content as Binary, alg))
/** JWT with header, payload, and signature by specific algorithm. valid algorithms dictated by HMACWith */
fun JWT(header: Object, payload: Object, signingKey: String, algorithm: String) = do {
var jwt = JWT(header, payload)
---
"$(jwt).$(signJWT(jwt, signingKey, algorithm))"
}
/** JWT with header, payload, and signed with HMAC-SHA256*/
fun JWT(header: Object, payload: Object, signingKey: String) = do {
JWT({ (header - 'alg' - 'typ'), typ: 'JWT', alg: 'HS256' }, payload, signingKey, 'HmacSHA256')
}
/** JWT with payload and automatically generated header, signed with HMAC-SHA256 */
fun JWT(payload: Object, signingKey: String) =
JWT({ typ: 'JWT', alg: 'HS256'}, payload, signingKey, 'HmacSHA256')
@mikeacjones
Copy link
Author

Usage:

JWT({ email: 'someone@something.com', campaignId: 890283e40e }, "signingKey")

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