forked from mirror/jwt
updated parsing errors to provide more feedback
This commit is contained in:
parent
f80fd39457
commit
1a8b763fae
89
jwt.go
89
jwt.go
|
@ -84,67 +84,100 @@ func (t *Token) SigningString() (string, error) {
|
||||||
// Parse, validate, and return a token.
|
// Parse, validate, and return a token.
|
||||||
// keyFunc will receive the parsed token and should return the key for validating.
|
// keyFunc will receive the parsed token and should return the key for validating.
|
||||||
// If everything is kosher, err will be nil
|
// If everything is kosher, err will be nil
|
||||||
func Parse(tokenString string, keyFunc Keyfunc) (token *Token, err error) {
|
func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
||||||
parts := strings.Split(tokenString, ".")
|
parts := strings.Split(tokenString, ".")
|
||||||
if len(parts) == 3 {
|
if len(parts) == 3 {
|
||||||
token = &Token{Raw: tokenString}
|
var err error
|
||||||
|
token := &Token{Raw: tokenString}
|
||||||
// parse Header
|
// parse Header
|
||||||
var headerBytes []byte
|
var headerBytes []byte
|
||||||
if headerBytes, err = DecodeSegment(parts[0]); err != nil {
|
if headerBytes, err = DecodeSegment(parts[0]); err != nil {
|
||||||
return
|
return token, &ValidationError{err: err.Error(), Malformed: true}
|
||||||
}
|
}
|
||||||
if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
|
if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
|
||||||
return
|
return token, &ValidationError{err: err.Error(), Malformed: true}
|
||||||
}
|
}
|
||||||
|
|
||||||
// parse Claims
|
// parse Claims
|
||||||
var claimBytes []byte
|
var claimBytes []byte
|
||||||
if claimBytes, err = DecodeSegment(parts[1]); err != nil {
|
if claimBytes, err = DecodeSegment(parts[1]); err != nil {
|
||||||
return
|
return token, &ValidationError{err: err.Error(), Malformed: true}
|
||||||
}
|
}
|
||||||
if err = json.Unmarshal(claimBytes, &token.Claims); err != nil {
|
if err = json.Unmarshal(claimBytes, &token.Claims); err != nil {
|
||||||
return
|
return token, &ValidationError{err: err.Error(), Malformed: true}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Lookup signature method
|
// Lookup signature method
|
||||||
if method, ok := token.Header["alg"].(string); ok {
|
if method, ok := token.Header["alg"].(string); ok {
|
||||||
if token.Method = GetSigningMethod(method); token.Method == nil {
|
if token.Method = GetSigningMethod(method); token.Method == nil {
|
||||||
err = errors.New("Signing method (alg) is unavailable.")
|
return token, &ValidationError{err: "Signing method (alg) is unavailable.", Unverifiable: true}
|
||||||
return
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
err = errors.New("Signing method (alg) is unspecified.")
|
return token, &ValidationError{err: "Signing method (alg) is unspecified.", Unverifiable: true}
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check expiration times
|
|
||||||
now := TimeFunc().Unix()
|
|
||||||
if exp, ok := token.Claims["exp"].(float64); ok {
|
|
||||||
if now > int64(exp) {
|
|
||||||
err = errors.New("Token is expired")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if nbf, ok := token.Claims["nbf"].(float64); ok {
|
|
||||||
if now < int64(nbf) {
|
|
||||||
err = errors.New("Token is not valid yet")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Lookup key
|
// Lookup key
|
||||||
var key []byte
|
var key []byte
|
||||||
if key, err = keyFunc(token); err != nil {
|
if key, err = keyFunc(token); err != nil {
|
||||||
return
|
return token, &ValidationError{err: err.Error(), Unverifiable: true}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check expiration times
|
||||||
|
vErr := &ValidationError{}
|
||||||
|
now := TimeFunc().Unix()
|
||||||
|
if exp, ok := token.Claims["exp"].(float64); ok {
|
||||||
|
if now > int64(exp) {
|
||||||
|
vErr.err = "Token is expired"
|
||||||
|
vErr.Expired = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if nbf, ok := token.Claims["nbf"].(float64); ok {
|
||||||
|
if now < int64(nbf) {
|
||||||
|
vErr.err = "Token is not valid yet"
|
||||||
|
vErr.NotValidYet = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Perform validation
|
// Perform validation
|
||||||
if err = token.Method.Verify(strings.Join(parts[0:2], "."), parts[2], key); err == nil {
|
if err = token.Method.Verify(strings.Join(parts[0:2], "."), parts[2], key); err != nil {
|
||||||
token.Valid = true
|
vErr.err = err.Error()
|
||||||
|
vErr.SignatureInvalid = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if vErr.Valid() {
|
||||||
|
token.Valid = true
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return token, vErr
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
err = errors.New("Token contains an invalid number of segments")
|
return nil, &ValidationError{err: "Token contains an invalid number of segments", Malformed: true}
|
||||||
}
|
}
|
||||||
return
|
}
|
||||||
|
|
||||||
|
type ValidationError struct {
|
||||||
|
err string
|
||||||
|
Malformed bool //Token is malformed
|
||||||
|
Unverifiable bool // Token could not be verified because of signing problems
|
||||||
|
SignatureInvalid bool // Signature validation failed
|
||||||
|
Expired bool // Exp validation failed
|
||||||
|
NotValidYet bool // NBF validation failed
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *ValidationError) Error() string {
|
||||||
|
if e.err == "" {
|
||||||
|
return "Token is invalid"
|
||||||
|
}
|
||||||
|
return e.err
|
||||||
|
}
|
||||||
|
|
||||||
|
// No errors
|
||||||
|
func (e *ValidationError) Valid() bool {
|
||||||
|
if e.Malformed || e.Unverifiable || e.SignatureInvalid || e.Expired || e.NotValidYet {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to find the token in an http.Request.
|
// Try to find the token in an http.Request.
|
||||||
|
|
66
jwt_test.go
66
jwt_test.go
|
@ -8,28 +8,64 @@ import (
|
||||||
"os"
|
"os"
|
||||||
"reflect"
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
var jwtTestData = []struct {
|
var jwtTestData = []struct {
|
||||||
name string
|
name string
|
||||||
tokenString string
|
tokenString string
|
||||||
claims map[string]interface{}
|
claims map[string]interface{}
|
||||||
valid bool
|
valid bool
|
||||||
|
validationError *ValidationError
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
"basic",
|
"basic",
|
||||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||||
map[string]interface{}{"foo": "bar"},
|
map[string]interface{}{"foo": "bar"},
|
||||||
true,
|
true,
|
||||||
|
nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"basic expired",
|
||||||
|
"", // autogen
|
||||||
|
map[string]interface{}{"foo": "bar", "exp": float64(time.Now().Unix() - 100)},
|
||||||
|
false,
|
||||||
|
&ValidationError{Expired: true},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"basic nbf",
|
||||||
|
"", // autogen
|
||||||
|
map[string]interface{}{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)},
|
||||||
|
false,
|
||||||
|
&ValidationError{NotValidYet: true},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"basic invalid",
|
"basic invalid",
|
||||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||||
map[string]interface{}{"foo": "bar"},
|
map[string]interface{}{"foo": "bar"},
|
||||||
false,
|
false,
|
||||||
|
&ValidationError{SignatureInvalid: true},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func makeSample(c map[string]interface{}) string {
|
||||||
|
file, _ := os.Open("test/sample_key")
|
||||||
|
buf := new(bytes.Buffer)
|
||||||
|
io.Copy(buf, file)
|
||||||
|
key := buf.Bytes()
|
||||||
|
file.Close()
|
||||||
|
|
||||||
|
token := New(GetSigningMethod("RS256"))
|
||||||
|
token.Claims = c
|
||||||
|
s, e := token.SignedString(key)
|
||||||
|
|
||||||
|
if e != nil {
|
||||||
|
panic(e.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
func TestJWT(t *testing.T) {
|
func TestJWT(t *testing.T) {
|
||||||
file, _ := os.Open("test/sample_key.pub")
|
file, _ := os.Open("test/sample_key.pub")
|
||||||
buf := new(bytes.Buffer)
|
buf := new(bytes.Buffer)
|
||||||
|
@ -38,17 +74,33 @@ func TestJWT(t *testing.T) {
|
||||||
file.Close()
|
file.Close()
|
||||||
|
|
||||||
for _, data := range jwtTestData {
|
for _, data := range jwtTestData {
|
||||||
|
if data.tokenString == "" {
|
||||||
|
data.tokenString = makeSample(data.claims)
|
||||||
|
}
|
||||||
|
|
||||||
token, err := Parse(data.tokenString, func(t *Token) ([]byte, error) { return key, nil })
|
token, err := Parse(data.tokenString, func(t *Token) ([]byte, error) { return key, nil })
|
||||||
|
|
||||||
if !reflect.DeepEqual(data.claims, token.Claims) {
|
if !reflect.DeepEqual(data.claims, token.Claims) {
|
||||||
t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims)
|
t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims)
|
||||||
}
|
}
|
||||||
if data.valid && err != nil {
|
if data.valid && err != nil {
|
||||||
t.Errorf("[%v] Error while verifying token: %v", data.name, err)
|
t.Errorf("[%v] Error while verifying token: %T:%v", data.name, err, err)
|
||||||
}
|
}
|
||||||
if !data.valid && err == nil {
|
if !data.valid && err == nil {
|
||||||
t.Errorf("[%v] Invalid token passed validation", data.name)
|
t.Errorf("[%v] Invalid token passed validation", data.name)
|
||||||
}
|
}
|
||||||
|
if data.validationError != nil {
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("[%v] Expecting error. Didn't get one.", data.name)
|
||||||
|
} else {
|
||||||
|
// perform deep equal without the string bit
|
||||||
|
err.(*ValidationError).err = ""
|
||||||
|
if !reflect.DeepEqual(data.validationError, err) {
|
||||||
|
t.Errorf("[%v] Errors don't match expectation", data.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -61,6 +113,10 @@ func TestParseRequest(t *testing.T) {
|
||||||
|
|
||||||
// Bearer token request
|
// Bearer token request
|
||||||
for _, data := range jwtTestData {
|
for _, data := range jwtTestData {
|
||||||
|
if data.tokenString == "" {
|
||||||
|
data.tokenString = makeSample(data.claims)
|
||||||
|
}
|
||||||
|
|
||||||
r, _ := http.NewRequest("GET", "/", nil)
|
r, _ := http.NewRequest("GET", "/", nil)
|
||||||
r.Header.Set("Authorization", fmt.Sprintf("Bearer %v", data.tokenString))
|
r.Header.Set("Authorization", fmt.Sprintf("Bearer %v", data.tokenString))
|
||||||
token, err := ParseFromRequest(r, func(t *Token) ([]byte, error) { return key, nil })
|
token, err := ParseFromRequest(r, func(t *Token) ([]byte, error) { return key, nil })
|
||||||
|
|
Loading…
Reference in New Issue