Last active
July 18, 2019 00:34
-
-
Save brackendev/303027dbcf5db0148397a12b836b8d73 to your computer and use it in GitHub Desktop.
[Pharo] Create and validate JSON Web Tokens
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
"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} |
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
| 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