Compute signature

This commit is contained in:
Matthew Dillon 2015-04-18 12:25:25 -08:00
parent 5d9f1a3b5f
commit f9557a80a3
2 changed files with 20 additions and 1 deletions

12
jwt.go
View file

@ -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))
}

View file

@ -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])
}
}