When possible, instead of identifying signing methods by string, pass

them in directly by name. This is less error-prone and avoids an unnecessary
map lookup. Also encourage this type of usage by using it in the README.
This commit is contained in:
Alex Browne 2014-12-27 14:14:23 -05:00
parent 47b263f020
commit bfe701fdf5
3 changed files with 4 additions and 6 deletions

View File

@ -34,7 +34,7 @@ Parsing and verifying tokens is pretty straight forward. You pass in the token
```go
// Create the token
token := jwt.New(jwt.GetSigningMethod("HS256"))
token := jwt.New(SigningMethodHS256)
// Set some claims
token.Claims["foo"] = "bar"
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

View File

@ -104,7 +104,7 @@ func makeSample(c map[string]interface{}) string {
panic(e.Error())
}
token := New(GetSigningMethod("RS256"))
token := New(SigningMethodRS256)
token.Claims = c
s, e := token.SignedString(key)

View File

@ -80,14 +80,13 @@ func TestRSASign(t *testing.T) {
func TestRSAVerifyWithPreParsedPrivateKey(t *testing.T) {
key, _ := ioutil.ReadFile("test/sample_key.pub")
method := GetSigningMethod("RS256").(*SigningMethodRSA)
parsedKey, err := ParseRSAPublicKeyFromPEM(key)
if err != nil {
t.Fatal(err)
}
testData := rsaTestData[0]
parts := strings.Split(testData.tokenString, ".")
err = method.Verify(strings.Join(parts[0:2], "."), parts[2], parsedKey)
err = SigningMethodRS256.Verify(strings.Join(parts[0:2], "."), parts[2], parsedKey)
if err != nil {
t.Errorf("[%v] Error while verifying key: %v", testData.name, err)
}
@ -95,14 +94,13 @@ func TestRSAVerifyWithPreParsedPrivateKey(t *testing.T) {
func TestRSAWithPreParsedPrivateKey(t *testing.T) {
key, _ := ioutil.ReadFile("test/sample_key")
method := GetSigningMethod("RS256").(*SigningMethodRSA)
parsedKey, err := ParseRSAPrivateKeyFromPEM(key)
if err != nil {
t.Fatal(err)
}
testData := rsaTestData[0]
parts := strings.Split(testData.tokenString, ".")
sig, err := method.Sign(strings.Join(parts[0:2], "."), parsedKey)
sig, err := SigningMethodRS256.Sign(strings.Join(parts[0:2], "."), parsedKey)
if err != nil {
t.Errorf("[%v] Error signing token: %v", testData.name, err)
}