jwt.go 6.71 KB
Newer Older
Dave Grijalva's avatar
Dave Grijalva committed
1 2 3 4 5
package jwt

import (
	"encoding/base64"
	"encoding/json"
Dave Grijalva's avatar
Dave Grijalva committed
6
	"errors"
Dave Grijalva's avatar
Dave Grijalva committed
7
	"net/http"
Dave Grijalva's avatar
Dave Grijalva committed
8 9
	"strings"
	"time"
Dave Grijalva's avatar
Dave Grijalva committed
10 11
)

12 13 14
// 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.
15 16
var TimeFunc = time.Now

17 18 19 20 21 22
// 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.
type Keyfunc func(*Token) ([]byte, error)

Dave Grijalva's avatar
Dave Grijalva committed
23 24
// A JWT Token
type Token struct {
Dave Grijalva's avatar
Dave Grijalva committed
25 26 27 28 29 30
	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
	Claims    map[string]interface{} // The second segment of the token
	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
Dave Grijalva's avatar
Dave Grijalva committed
31 32
}

Dave Grijalva's avatar
Dave Grijalva committed
33
// Create a new Token.  Takes a signing method
Dave Grijalva's avatar
Dave Grijalva committed
34
func New(method SigningMethod) *Token {
35 36 37 38 39 40
	return &Token{
		Header: map[string]interface{}{
			"typ": "JWT",
			"alg": method.Alg(),
		},
		Claims: make(map[string]interface{}),
Dave Grijalva's avatar
Dave Grijalva committed
41
		Method: method,
42 43 44
	}
}

Dave Grijalva's avatar
Dave Grijalva committed
45
// Get the complete, signed token
Dave Grijalva's avatar
Dave Grijalva committed
46
func (t *Token) SignedString(key []byte) (string, error) {
Dave Grijalva's avatar
Dave Grijalva committed
47 48 49 50 51 52 53 54 55
	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
56 57
}

Dave Grijalva's avatar
Dave Grijalva committed
58 59 60 61
// 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.
Dave Grijalva's avatar
Dave Grijalva committed
62
func (t *Token) SigningString() (string, error) {
Dave Grijalva's avatar
Dave Grijalva committed
63 64 65 66 67 68 69 70 71
	var err error
	parts := make([]string, 2)
	for i, _ := range parts {
		var source map[string]interface{}
		if i == 0 {
			source = t.Header
		} else {
			source = t.Claims
		}
Dave Grijalva's avatar
Dave Grijalva committed
72

Dave Grijalva's avatar
Dave Grijalva committed
73 74 75 76
		var jsonValue []byte
		if jsonValue, err = json.Marshal(source); err != nil {
			return "", err
		}
Dave Grijalva's avatar
Dave Grijalva committed
77

Dave Grijalva's avatar
Dave Grijalva committed
78 79 80
		parts[i] = EncodeSegment(jsonValue)
	}
	return strings.Join(parts, "."), nil
81 82
}

Dave Grijalva's avatar
Dave Grijalva committed
83 84 85
// 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
86
func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
Dave Grijalva's avatar
Dave Grijalva committed
87
	parts := strings.Split(tokenString, ".")
Cenk Alti's avatar
Cenk Alti committed
88 89 90
	if len(parts) != 3 {
		return nil, &ValidationError{err: "Token contains an invalid number of segments", Errors: ValidationErrorMalformed}
	}
Dave Grijalva's avatar
Dave Grijalva committed
91

Cenk Alti's avatar
Cenk Alti committed
92 93 94 95 96 97 98 99 100 101
	var err error
	token := &Token{Raw: tokenString}
	// 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}
	}
Dave Grijalva's avatar
Dave Grijalva committed
102

Cenk Alti's avatar
Cenk Alti committed
103 104 105 106 107 108 109 110
	// parse Claims
	var claimBytes []byte
	if claimBytes, err = DecodeSegment(parts[1]); err != nil {
		return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
	}
	if err = json.Unmarshal(claimBytes, &token.Claims); err != nil {
		return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
	}
111

Cenk Alti's avatar
Cenk Alti committed
112 113 114 115
	// Lookup signature method
	if method, ok := token.Header["alg"].(string); ok {
		if token.Method = GetSigningMethod(method); token.Method == nil {
			return token, &ValidationError{err: "Signing method (alg) is unavailable.", Errors: ValidationErrorUnverifiable}
Dave Grijalva's avatar
Dave Grijalva committed
116
		}
Cenk Alti's avatar
Cenk Alti committed
117 118 119
	} else {
		return token, &ValidationError{err: "Signing method (alg) is unspecified.", Errors: ValidationErrorUnverifiable}
	}
Dave Grijalva's avatar
Dave Grijalva committed
120

Cenk Alti's avatar
Cenk Alti committed
121 122 123 124 125
	// Lookup key
	var key []byte
	if key, err = keyFunc(token); err != nil {
		return token, &ValidationError{err: err.Error(), Errors: ValidationErrorUnverifiable}
	}
Dave Grijalva's avatar
Dave Grijalva committed
126

Cenk Alti's avatar
Cenk Alti committed
127 128 129 130 131 132 133
	// 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.Errors |= ValidationErrorExpired
Dave Grijalva's avatar
Dave Grijalva committed
134
		}
Cenk Alti's avatar
Cenk Alti committed
135 136 137 138 139
	}
	if nbf, ok := token.Claims["nbf"].(float64); ok {
		if now < int64(nbf) {
			vErr.err = "Token is not valid yet"
			vErr.Errors |= ValidationErrorNotValidYet
Dave Grijalva's avatar
Dave Grijalva committed
140
		}
Cenk Alti's avatar
Cenk Alti committed
141
	}
Dave Grijalva's avatar
Dave Grijalva committed
142

Cenk Alti's avatar
Cenk Alti committed
143 144 145 146 147
	// Perform validation
	if err = token.Method.Verify(strings.Join(parts[0:2], "."), parts[2], key); err != nil {
		vErr.err = err.Error()
		vErr.Errors |= ValidationErrorSignatureInvalid
	}
148

Cenk Alti's avatar
Cenk Alti committed
149 150 151
	if vErr.valid() {
		token.Valid = true
		return token, nil
152
	}
Cenk Alti's avatar
Cenk Alti committed
153 154

	return token, vErr
155 156
}

Dave Grijalva's avatar
Dave Grijalva committed
157
// The errors that might occur when parsing and validating a token
158 159 160 161 162 163 164 165
const (
	ValidationErrorMalformed        uint32 = 1 << iota // Token is malformed
	ValidationErrorUnverifiable                        // Token could not be verified because of signing problems
	ValidationErrorSignatureInvalid                    // Signature validation failed
	ValidationErrorExpired                             // Exp validation failed
	ValidationErrorNotValidYet                         // NBF validation failed
)

Dave Grijalva's avatar
Dave Grijalva committed
166
// The error from Parse if token is not valid
167
type ValidationError struct {
168 169
	err    string
	Errors uint32 // bitfield.  see ValidationError... constants
170 171
}

Dave Grijalva's avatar
Dave Grijalva committed
172
// Validation error is an error type
173
func (e ValidationError) Error() string {
174 175 176 177 178 179 180
	if e.err == "" {
		return "Token is invalid"
	}
	return e.err
}

// No errors
Dave Grijalva's avatar
Dave Grijalva committed
181
func (e *ValidationError) valid() bool {
182
	if e.Errors > 0 {
183
		return false
Dave Grijalva's avatar
Dave Grijalva committed
184
	}
185
	return true
Dave Grijalva's avatar
Dave Grijalva committed
186
}
Dave Grijalva's avatar
Dave Grijalva committed
187

Dave Grijalva's avatar
Dave Grijalva committed
188
// Try to find the token in an http.Request.
189 190 191
// 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.
192
func ParseFromRequest(req *http.Request, keyFunc Keyfunc) (token *Token, err error) {
Dave Grijalva's avatar
Dave Grijalva committed
193

194 195 196 197 198 199 200
	// 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" {
			return Parse(ah[7:], keyFunc)
		}
	}
Dave Grijalva's avatar
Dave Grijalva committed
201

202
	// Look for "access_token" parameter
Dave Grijalva's avatar
Dave Grijalva committed
203
	req.ParseMultipartForm(10e6)
204 205 206 207
	if tokStr := req.Form.Get("access_token"); tokStr != "" {
		return Parse(tokStr, keyFunc)
	}

208
	return nil, errors.New("No token present in request.")
Dave Grijalva's avatar
Dave Grijalva committed
209

Dave Grijalva's avatar
Dave Grijalva committed
210 211
}

Dave Grijalva's avatar
Dave Grijalva committed
212
// Encode JWT specific base64url encoding with padding stripped
Dave Grijalva's avatar
Dave Grijalva committed
213
func EncodeSegment(seg []byte) string {
214 215 216
	return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
}

Dave Grijalva's avatar
Dave Grijalva committed
217
// Decode JWT specific base64url encoding with padding stripped
Dave Grijalva's avatar
Dave Grijalva committed
218
func DecodeSegment(seg string) ([]byte, error) {
219 220
	if l := len(seg) % 4; l > 0 {
		seg += strings.Repeat("=", 4-l)
Dave Grijalva's avatar
Dave Grijalva committed
221
	}
Dave Grijalva's avatar
Dave Grijalva committed
222

Dave Grijalva's avatar
Dave Grijalva committed
223
	return base64.URLEncoding.DecodeString(seg)
Dave Grijalva's avatar
Dave Grijalva committed
224
}