From 40be3976280e146ab91f06f58508ebd8e24fd9a6 Mon Sep 17 00:00:00 2001 From: kaygit <> Date: Wed, 27 Jul 2016 16:33:22 +0200 Subject: [PATCH] Making tokens url safe to be JWT compatible StdEncoding is used for standard base64 encoding. The base64 alphabet includes '+', '/' and '=' characters which are not URL safe and not JWT compatible. Furthermore padding '=' characters are added, but the JWT defenition want it to be compact. Using RawURLEncoding instead of StdEncoding solve this issues. --- jwt.go | 4 ++-- jwt_test.go | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/jwt.go b/jwt.go index 353563e..baf7f12 100644 --- a/jwt.go +++ b/jwt.go @@ -314,9 +314,9 @@ func encode(s interface{}) (string, error) { default: return "", ErrEncoding } - return base64.StdEncoding.EncodeToString(r), nil + return base64.RawURLEncoding.EncodeToString(r), nil } func decode(s string) ([]byte, error) { - return base64.StdEncoding.DecodeString(s) + return base64.RawURLEncoding.DecodeString(s) } diff --git a/jwt_test.go b/jwt_test.go index 01db635..56b06e4 100644 --- a/jwt_test.go +++ b/jwt_test.go @@ -136,12 +136,12 @@ func TestGenerateTokenHandler(t *testing.T) { token, m := newToken(t) j := strings.Split(token, ".") - header := base64.StdEncoding.EncodeToString([]byte(`{"typ":"JWT","alg":"HS256"}`)) + header := base64.RawURLEncoding.EncodeToString([]byte(`{"typ":"JWT","alg":"HS256"}`)) if j[0] != header { t.Errorf("wanted %v, got %v", header, j[0]) } - claims, err := base64.StdEncoding.DecodeString(j[1]) + claims, err := base64.RawURLEncoding.DecodeString(j[1]) var c struct { Exp int Iat int @@ -158,7 +158,7 @@ func TestGenerateTokenHandler(t *testing.T) { mac := hmac.New(sha256.New, []byte(m.secret)) message := []byte(strings.Join([]string{j[0], j[1]}, ".")) mac.Write(message) - expectedMac := base64.StdEncoding.EncodeToString(mac.Sum(nil)) + expectedMac := base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) if !hmac.Equal([]byte(j[2]), []byte(expectedMac)) { t.Errorf("wanted %v, got %v", expectedMac, j[2]) }