Skip to content

Instantly share code, notes, and snippets.

@brackendev
Last active July 18, 2019 00:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brackendev/303027dbcf5db0148397a12b836b8d73 to your computer and use it in GitHub Desktop.
Save brackendev/303027dbcf5db0148397a12b836b8d73 to your computer and use it in GitHub Desktop.
[Pharo] Create and validate JSON Web Tokens
"Signature validates on www.jwt.io"
| dictToSign secret headerD headerJ headerE payloadJ payloadE joined signed signedE |
dictToSign := Dictionary new at: 'test' put: 123.
secret := 'secret'.
"Don't change below"
headerD := Dictionary new at: 'alg' put: 'HS256'; at: 'typ' put: 'JWT'; yourself.
headerJ := NeoJSONWriter toString: headerD.
headerE := ZnBase64Encoder new encode: (ZnUTF8Encoder new encodeString: headerJ) asByteArray.
payloadJ := NeoJSONWriter toString: dictToSign.
payloadE := ZnBase64Encoder new encode: (ZnUTF8Encoder new encodeString: payloadJ) asByteArray.
joined := $. join: {headerE. payloadE}.
signed := (HMAC on: SHA256) key: secret asByteArray; digestMessage: joined asByteArray.
signedE := ZnBase64Encoder new encode: signed.
^ $. join: {headerE. payloadE. signedE}
| jwt secret split header payload signature joined signed signedE |
jwt := 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.MTIz.vwkaUhx9uogHdSWlSU6jssr1Ot3yys+8Ehc7Nfx3LwQ='.
secret := 'secret'.
"Don't change below"
split := $. split: jwt.
header := split first.
payload := split second.
signature := split third.
joined := $. join: {header. payload}.
signed := (HMAC on: SHA256) key: secret asByteArray; digestMessage: joined asByteArray.
signedE := ZnBase64Encoder new encode: signed.
[ signature last ~= $= and: signedE last = $= ]
whileTrue: [ signedE := signedE allButLast: 1 ].
^ signature = signedE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment