2012-04-18 03:49:21 +04:00
|
|
|
package jwt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"encoding/json"
|
2012-04-18 23:18:31 +04:00
|
|
|
"net/http"
|
2012-04-18 23:59:37 +04:00
|
|
|
"strings"
|
|
|
|
"time"
|
2012-04-18 03:49:21 +04:00
|
|
|
)
|
|
|
|
|
2014-02-11 05:27:59 +04:00
|
|
|
// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time).
|
|
|
|
// You can override it to use another time value. This is useful for testing or if your
|
|
|
|
// server uses a different time zone than your tokens.
|
2014-02-06 03:07:40 +04:00
|
|
|
var TimeFunc = time.Now
|
|
|
|
|
2012-07-07 03:16:34 +04:00
|
|
|
// Parse methods use this callback function to supply
|
|
|
|
// the key for verification. The function receives the parsed,
|
|
|
|
// but unverified Token. This allows you to use propries in the
|
|
|
|
// Header of the token (such as `kid`) to identify which key to use.
|
2014-08-04 22:26:53 +04:00
|
|
|
type Keyfunc func(*Token) (interface{}, error)
|
2012-07-07 03:16:34 +04:00
|
|
|
|
2014-06-16 06:40:38 +04:00
|
|
|
// A JWT Token. Different fields will be used depending on whether you're
|
|
|
|
// creating or parsing/verifying a token.
|
2012-04-18 03:49:21 +04:00
|
|
|
type Token struct {
|
2014-06-16 06:39:12 +04:00
|
|
|
Raw string // The raw token. Populated when you Parse a token
|
|
|
|
Method SigningMethod // The signing method used or to be used
|
|
|
|
Header map[string]interface{} // The first segment of the token
|
2015-07-17 21:59:18 +03:00
|
|
|
Claims Claims // The second segment of the token
|
2014-06-16 06:39:12 +04:00
|
|
|
Signature string // The third segment of the token. Populated when you Parse a token
|
|
|
|
Valid bool // Is the token valid? Populated when you Parse/Verify a token
|
2012-04-18 03:49:21 +04:00
|
|
|
}
|
|
|
|
|
2014-06-16 06:39:12 +04:00
|
|
|
// Create a new Token. Takes a signing method
|
2012-07-07 04:02:20 +04:00
|
|
|
func New(method SigningMethod) *Token {
|
2015-07-20 20:45:40 +03:00
|
|
|
return NewWithClaims(method, MapClaim{})
|
2012-07-07 02:43:17 +04:00
|
|
|
}
|
|
|
|
|
2015-07-17 21:59:18 +03:00
|
|
|
func NewWithClaims(method SigningMethod, claims Claims) *Token {
|
2015-07-14 20:34:09 +03:00
|
|
|
return &Token{
|
|
|
|
Header: map[string]interface{}{
|
|
|
|
"typ": "JWT",
|
|
|
|
"alg": method.Alg(),
|
|
|
|
},
|
|
|
|
Claims: claims,
|
|
|
|
Method: method,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-07-07 03:12:33 +04:00
|
|
|
// Get the complete, signed token
|
2014-09-29 22:00:25 +04:00
|
|
|
func (t *Token) SignedString(key interface{}) (string, error) {
|
2012-07-07 03:07:55 +04:00
|
|
|
var sig, sstr string
|
|
|
|
var err error
|
|
|
|
if sstr, err = t.SigningString(); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if sig, err = t.Method.Sign(sstr, key); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return strings.Join([]string{sstr, sig}, "."), nil
|
2012-07-07 02:43:17 +04:00
|
|
|
}
|
|
|
|
|
2012-07-07 03:12:33 +04:00
|
|
|
// Generate the signing string. This is the
|
|
|
|
// most expensive part of the whole deal. Unless you
|
|
|
|
// need this for something special, just go straight for
|
|
|
|
// the SignedString.
|
2012-07-07 04:02:20 +04:00
|
|
|
func (t *Token) SigningString() (string, error) {
|
2012-07-07 03:07:55 +04:00
|
|
|
var err error
|
|
|
|
parts := make([]string, 2)
|
|
|
|
for i, _ := range parts {
|
2015-07-13 22:14:12 +03:00
|
|
|
var jsonValue []byte
|
2012-07-07 03:07:55 +04:00
|
|
|
if i == 0 {
|
2015-07-13 22:14:12 +03:00
|
|
|
if jsonValue, err = json.Marshal(t.Header); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2012-07-07 03:07:55 +04:00
|
|
|
} else {
|
2015-07-13 22:14:12 +03:00
|
|
|
if jsonValue, err = json.Marshal(t.Claims); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2012-07-07 03:07:55 +04:00
|
|
|
}
|
2012-07-07 04:02:20 +04:00
|
|
|
|
2012-07-07 03:07:55 +04:00
|
|
|
parts[i] = EncodeSegment(jsonValue)
|
|
|
|
}
|
|
|
|
return strings.Join(parts, "."), nil
|
2012-07-07 02:43:17 +04:00
|
|
|
}
|
|
|
|
|
2012-04-18 10:25:22 +04:00
|
|
|
// Parse, validate, and return a token.
|
|
|
|
// keyFunc will receive the parsed token and should return the key for validating.
|
|
|
|
// If everything is kosher, err will be nil
|
2014-03-08 02:43:11 +04:00
|
|
|
func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
2015-07-17 21:55:06 +03:00
|
|
|
return ParseWithClaims(tokenString, keyFunc, &MapClaim{})
|
2015-07-14 20:34:09 +03:00
|
|
|
}
|
|
|
|
|
2015-07-17 21:59:18 +03:00
|
|
|
func ParseWithClaims(tokenString string, keyFunc Keyfunc, claims Claims) (*Token, error) {
|
2012-04-18 03:49:21 +04:00
|
|
|
parts := strings.Split(tokenString, ".")
|
2014-06-02 12:28:16 +04:00
|
|
|
if len(parts) != 3 {
|
2014-09-08 05:42:58 +04:00
|
|
|
return nil, &ValidationError{err: "token contains an invalid number of segments", Errors: ValidationErrorMalformed}
|
2014-06-02 12:28:16 +04:00
|
|
|
}
|
2012-04-18 23:59:37 +04:00
|
|
|
|
2014-06-02 12:28:16 +04:00
|
|
|
var err error
|
2015-07-14 20:34:09 +03:00
|
|
|
token := &Token{
|
|
|
|
Raw: tokenString,
|
|
|
|
}
|
|
|
|
|
2014-06-02 12:28:16 +04:00
|
|
|
// parse Header
|
|
|
|
var headerBytes []byte
|
|
|
|
if headerBytes, err = DecodeSegment(parts[0]); err != nil {
|
|
|
|
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
|
|
|
|
}
|
|
|
|
if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
|
|
|
|
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
|
|
|
|
}
|
2012-04-18 23:59:37 +04:00
|
|
|
|
2014-06-02 12:28:16 +04:00
|
|
|
// parse Claims
|
|
|
|
var claimBytes []byte
|
2015-07-14 20:34:09 +03:00
|
|
|
|
2014-06-02 12:28:16 +04:00
|
|
|
if claimBytes, err = DecodeSegment(parts[1]); err != nil {
|
|
|
|
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
|
|
|
|
}
|
2015-07-14 20:34:09 +03:00
|
|
|
|
|
|
|
if err = json.Unmarshal(claimBytes, &claims); err != nil {
|
2014-06-02 12:28:16 +04:00
|
|
|
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
|
|
|
|
}
|
2015-07-17 20:28:08 +03:00
|
|
|
|
2015-07-14 20:34:09 +03:00
|
|
|
token.Claims = claims
|
2014-03-08 02:43:11 +04:00
|
|
|
|
2014-06-02 12:28:16 +04:00
|
|
|
// Lookup signature method
|
|
|
|
if method, ok := token.Header["alg"].(string); ok {
|
|
|
|
if token.Method = GetSigningMethod(method); token.Method == nil {
|
2014-09-08 05:42:58 +04:00
|
|
|
return token, &ValidationError{err: "signing method (alg) is unavailable.", Errors: ValidationErrorUnverifiable}
|
2012-04-18 03:49:21 +04:00
|
|
|
}
|
2014-06-02 12:28:16 +04:00
|
|
|
} else {
|
2014-09-08 05:42:58 +04:00
|
|
|
return token, &ValidationError{err: "signing method (alg) is unspecified.", Errors: ValidationErrorUnverifiable}
|
2014-06-02 12:28:16 +04:00
|
|
|
}
|
2012-04-18 03:49:21 +04:00
|
|
|
|
2014-06-02 12:28:16 +04:00
|
|
|
// Lookup key
|
2014-08-04 22:26:53 +04:00
|
|
|
var key interface{}
|
2014-10-12 00:54:16 +04:00
|
|
|
if keyFunc == nil {
|
|
|
|
// keyFunc was not provided. short circuiting validation
|
|
|
|
return token, &ValidationError{err: "no Keyfunc was provided.", Errors: ValidationErrorUnverifiable}
|
|
|
|
}
|
2014-06-02 12:28:16 +04:00
|
|
|
if key, err = keyFunc(token); err != nil {
|
2014-10-12 00:54:16 +04:00
|
|
|
// keyFunc returned an error
|
2014-06-02 12:28:16 +04:00
|
|
|
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorUnverifiable}
|
|
|
|
}
|
2012-04-18 03:49:21 +04:00
|
|
|
|
2015-07-17 20:28:08 +03:00
|
|
|
vErr := &ValidationError{}
|
2015-07-14 20:34:09 +03:00
|
|
|
|
2015-07-17 17:35:56 +03:00
|
|
|
// Validate Claims
|
|
|
|
if err := token.Claims.Valid(); err != nil {
|
|
|
|
|
|
|
|
// If the Claims Valid returned an error, check if it is a validation error,
|
|
|
|
// If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set
|
2015-07-14 20:34:09 +03:00
|
|
|
if e, ok := err.(*ValidationError); !ok {
|
|
|
|
vErr = &ValidationError{err: err.Error(), Errors: ValidationErrorClaimsInvalid}
|
|
|
|
} else {
|
|
|
|
vErr = e
|
|
|
|
}
|
|
|
|
}
|
2012-04-18 23:59:37 +04:00
|
|
|
|
2014-06-02 12:28:16 +04:00
|
|
|
// Perform validation
|
|
|
|
if err = token.Method.Verify(strings.Join(parts[0:2], "."), parts[2], key); err != nil {
|
|
|
|
vErr.err = err.Error()
|
|
|
|
vErr.Errors |= ValidationErrorSignatureInvalid
|
|
|
|
}
|
2014-03-08 02:43:11 +04:00
|
|
|
|
2015-07-17 20:28:08 +03:00
|
|
|
if vErr.valid() {
|
2014-06-02 12:28:16 +04:00
|
|
|
token.Valid = true
|
|
|
|
return token, nil
|
2014-03-08 02:43:11 +04:00
|
|
|
}
|
2014-06-02 12:28:16 +04:00
|
|
|
|
|
|
|
return token, vErr
|
2014-03-08 02:43:11 +04:00
|
|
|
}
|
|
|
|
|
2012-07-07 03:12:33 +04:00
|
|
|
// Try to find the token in an http.Request.
|
2012-07-07 23:38:18 +04:00
|
|
|
// This method will call ParseMultipartForm if there's no token in the header.
|
|
|
|
// Currently, it looks in the Authorization header as well as
|
|
|
|
// looking for an 'access_token' request parameter in req.Form.
|
2012-07-07 03:16:34 +04:00
|
|
|
func ParseFromRequest(req *http.Request, keyFunc Keyfunc) (token *Token, err error) {
|
2015-07-17 21:59:18 +03:00
|
|
|
return ParseFromRequestWithClaims(req, keyFunc, &MapClaim{})
|
2015-07-17 20:28:08 +03:00
|
|
|
}
|
2012-04-18 23:18:31 +04:00
|
|
|
|
2015-07-17 21:59:18 +03:00
|
|
|
func ParseFromRequestWithClaims(req *http.Request, keyFunc Keyfunc, claims Claims) (token *Token, err error) {
|
2012-04-18 23:35:16 +04:00
|
|
|
// Look for an Authorization header
|
|
|
|
if ah := req.Header.Get("Authorization"); ah != "" {
|
|
|
|
// Should be a bearer token
|
|
|
|
if len(ah) > 6 && strings.ToUpper(ah[0:6]) == "BEARER" {
|
2015-07-17 20:28:08 +03:00
|
|
|
return ParseWithClaims(ah[7:], keyFunc, claims)
|
2012-04-18 23:35:16 +04:00
|
|
|
}
|
|
|
|
}
|
2012-04-18 23:59:37 +04:00
|
|
|
|
2012-07-07 23:38:18 +04:00
|
|
|
// Look for "access_token" parameter
|
2012-07-07 23:40:24 +04:00
|
|
|
req.ParseMultipartForm(10e6)
|
2012-07-07 23:38:18 +04:00
|
|
|
if tokStr := req.Form.Get("access_token"); tokStr != "" {
|
2015-07-17 20:28:08 +03:00
|
|
|
return ParseWithClaims(tokStr, keyFunc, claims)
|
2012-07-07 23:38:18 +04:00
|
|
|
}
|
|
|
|
|
2014-10-20 09:09:02 +04:00
|
|
|
return nil, ErrNoTokenInRequest
|
2012-04-18 23:18:31 +04:00
|
|
|
}
|
|
|
|
|
2012-07-07 03:12:33 +04:00
|
|
|
// Encode JWT specific base64url encoding with padding stripped
|
2012-07-07 04:02:20 +04:00
|
|
|
func EncodeSegment(seg []byte) string {
|
2012-07-07 02:43:17 +04:00
|
|
|
return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
|
|
|
|
}
|
|
|
|
|
2012-07-07 03:12:33 +04:00
|
|
|
// Decode JWT specific base64url encoding with padding stripped
|
2012-04-18 23:59:37 +04:00
|
|
|
func DecodeSegment(seg string) ([]byte, error) {
|
2014-06-03 18:15:11 +04:00
|
|
|
if l := len(seg) % 4; l > 0 {
|
|
|
|
seg += strings.Repeat("=", 4-l)
|
2012-04-18 23:18:31 +04:00
|
|
|
}
|
2012-04-18 23:59:37 +04:00
|
|
|
|
2012-04-18 23:18:31 +04:00
|
|
|
return base64.URLEncoding.DecodeString(seg)
|
2012-04-18 23:59:37 +04:00
|
|
|
}
|