2012-04-18 03:49:21 +04:00
|
|
|
package jwt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
"errors"
|
|
|
|
"encoding/base64"
|
|
|
|
"encoding/json"
|
2012-04-18 03:52:38 +04:00
|
|
|
"time"
|
2012-04-18 03:49:21 +04:00
|
|
|
)
|
|
|
|
|
|
|
|
// A JWT Token
|
|
|
|
type Token struct {
|
|
|
|
Header map[string]interface{}
|
|
|
|
Claims map[string]interface{}
|
|
|
|
Method SigningMethod
|
|
|
|
Signature string
|
|
|
|
Valid bool
|
|
|
|
}
|
|
|
|
|
2012-04-18 03:58:52 +04:00
|
|
|
func Parse(tokenString string, keyFunc func(*Token)([]byte, error)) (token *Token, err error) {
|
2012-04-18 03:49:21 +04:00
|
|
|
parts := strings.Split(tokenString, ".")
|
|
|
|
if len(parts) == 3 {
|
|
|
|
token = new(Token)
|
|
|
|
// parse Header
|
|
|
|
var headerBytes []byte
|
|
|
|
if headerBytes, err = base64.URLEncoding.DecodeString(parts[0]); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// parse Claims
|
|
|
|
var claimBytes []byte
|
2012-04-18 03:58:52 +04:00
|
|
|
if claimBytes, err = base64.URLEncoding.DecodeString(parts[1]); err != nil {
|
2012-04-18 03:49:21 +04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if err = json.Unmarshal(claimBytes, &token.Claims); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Lookup signature method
|
|
|
|
if method, ok := token.Header["alg"].(string); ok {
|
|
|
|
if token.Method, err = GetSigningMethod(method); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
err = errors.New("Signing method (alg) is unspecified.")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check expiry times
|
2012-04-18 03:52:38 +04:00
|
|
|
if exp, ok := token.Claims["exp"].(float64); ok {
|
|
|
|
if time.Now().Unix() > int64(exp) {
|
|
|
|
err = errors.New("Token is expired")
|
|
|
|
}
|
|
|
|
}
|
2012-04-18 03:49:21 +04:00
|
|
|
|
|
|
|
// Lookup key
|
2012-04-18 03:58:52 +04:00
|
|
|
var key []byte
|
|
|
|
if key, err = keyFunc(token); err != nil {
|
|
|
|
return
|
|
|
|
}
|
2012-04-18 03:49:21 +04:00
|
|
|
|
2012-04-18 03:58:52 +04:00
|
|
|
// Perform validation
|
2012-04-18 09:50:26 +04:00
|
|
|
if err = token.Method.Verify(strings.Join(parts[0:2], "."), parts[2], key); err == nil {
|
2012-04-18 03:58:52 +04:00
|
|
|
token.Valid = true
|
|
|
|
}
|
2012-04-18 03:49:21 +04:00
|
|
|
|
|
|
|
} else {
|
|
|
|
err = errors.New("Token contains an invalid number of segments")
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|