Skip to content

Instantly share code, notes, and snippets.

@rschultheis
Created July 24, 2019 21:55
Show Gist options
  • Save rschultheis/bab55f4319c656b52d051819e0402e1f to your computer and use it in GitHub Desktop.
Save rschultheis/bab55f4319c656b52d051819e0402e1f to your computer and use it in GitHub Desktop.
decoding JWT in GO experiment
package jwtdecode
import (
"encoding/base64"
"strings"
)
type JWTBlob struct {
RawJWT string
}
func (j JWTBlob) Parts() []string {
return strings.Split(j.RawJWT, ".")
}
func (j JWTBlob) PayloadPart() string {
return j.Parts()[1]
}
// shamelessly stolen from https://github.com/dgrijalva/jwt-go/blob/06ea1031745cb8b3dab3f6a236daf2b0aa468b7e/token.go#L102
func (j JWTBlob) DecodedPayloadPart() ([]byte, error) {
seg := j.PayloadPart()
if l := len(seg) % 4; l > 0 {
seg += strings.Repeat("=", 4-l)
}
return base64.URLEncoding.DecodeString(seg)
}
package jwtdecode
import (
"testing"
"github.com/stretchr/testify/assert"
)
const (
jwt_example_a = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ.-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM"
)
func TestParts(t *testing.T) {
assert := assert.New(t)
jwtblob := JWTBlob{RawJWT: jwt_example_a}
actual_parts := jwtblob.Parts()
expected_parts := []string{
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9",
"eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ",
"-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM",
}
assert.Equal(expected_parts, actual_parts, "should be equal")
}
func TestPayloadPart(t *testing.T) {
assert := assert.New(t)
jwtblob := JWTBlob{RawJWT: jwt_example_a}
actual_payload_part := jwtblob.PayloadPart()
expected_payload_part := "eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ"
assert.Equal(expected_payload_part, actual_payload_part)
}
func TestDecodedPayloadPart(t *testing.T) {
assert := assert.New(t)
jwtblob := JWTBlob{RawJWT: jwt_example_a}
actual_decoded_payload, _ := jwtblob.DecodedPayloadPart()
expected_decoded_payload := `{"userId":"b08f86af-35da-48f2-8fab-cef3904660bd"}`
assert.Equal(expected_decoded_payload, string(actual_decoded_payload))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment