From f9557a80a35a7809c4c756502dd160fea0d2f998 Mon Sep 17 00:00:00 2001 From: Matthew Dillon Date: Sat, 18 Apr 2015 12:25:25 -0800 Subject: [PATCH] Compute signature --- jwt.go | 12 +++++++++++- jwt_test.go | 9 +++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/jwt.go b/jwt.go index 52a066b..e300664 100644 --- a/jwt.go +++ b/jwt.go @@ -1,6 +1,8 @@ package jwt import ( + "crypto/hmac" + "crypto/sha256" "encoding/base64" "encoding/json" "errors" @@ -95,8 +97,16 @@ func (m *JWTMiddleware) GenerateToken(w http.ResponseWriter, r *http.Request) { panic(err) } - response := strings.Join([]string{header, claimsSet}, ".") + toSig := strings.Join([]string{header, claimsSet}, ".") + h := hmac.New(sha256.New, []byte(m.secret)) + h.Write([]byte(toSig)) + sig, err := encode(h.Sum(nil)) + if err != nil { + panic(err) + } + + response := strings.Join([]string{toSig, sig}, ".") w.Write([]byte(response)) } diff --git a/jwt_test.go b/jwt_test.go index 8b14044..0f97934 100644 --- a/jwt_test.go +++ b/jwt_test.go @@ -2,6 +2,8 @@ package jwt import ( "bytes" + "crypto/hmac" + "crypto/sha256" "encoding/base64" "encoding/json" "io/ioutil" @@ -139,4 +141,11 @@ func TestGenerateTokenHandler(t *testing.T) { if duration != d { t.Errorf("wanted %v, got %v", d, duration) } + mac := hmac.New(sha256.New, []byte(middleware.secret)) + message := []byte(strings.Join([]string{j[0], j[1]}, ".")) + mac.Write(message) + expectedMac := base64.StdEncoding.EncodeToString(mac.Sum(nil)) + if !hmac.Equal([]byte(j[2]), []byte(expectedMac)) { + t.Errorf("wanted %v, got %v", expectedMac, j[2]) + } }