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.
This commit is contained in:
kaygit 2016-07-27 16:33:22 +02:00
parent 0c914e9b3a
commit 40be397628
2 changed files with 5 additions and 5 deletions

4
jwt.go
View file

@ -314,9 +314,9 @@ func encode(s interface{}) (string, error) {
default: default:
return "", ErrEncoding return "", ErrEncoding
} }
return base64.StdEncoding.EncodeToString(r), nil return base64.RawURLEncoding.EncodeToString(r), nil
} }
func decode(s string) ([]byte, error) { func decode(s string) ([]byte, error) {
return base64.StdEncoding.DecodeString(s) return base64.RawURLEncoding.DecodeString(s)
} }

View file

@ -136,12 +136,12 @@ func TestGenerateTokenHandler(t *testing.T) {
token, m := newToken(t) token, m := newToken(t)
j := strings.Split(token, ".") 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 { if j[0] != header {
t.Errorf("wanted %v, got %v", header, j[0]) 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 { var c struct {
Exp int Exp int
Iat int Iat int
@ -158,7 +158,7 @@ func TestGenerateTokenHandler(t *testing.T) {
mac := hmac.New(sha256.New, []byte(m.secret)) mac := hmac.New(sha256.New, []byte(m.secret))
message := []byte(strings.Join([]string{j[0], j[1]}, ".")) message := []byte(strings.Join([]string{j[0], j[1]}, "."))
mac.Write(message) 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)) { if !hmac.Equal([]byte(j[2]), []byte(expectedMac)) {
t.Errorf("wanted %v, got %v", expectedMac, j[2]) t.Errorf("wanted %v, got %v", expectedMac, j[2])
} }