jwt/jwt.go

226 lines
6.5 KiB
Go
Raw Normal View History

2012-04-18 03:49:21 +04:00
package jwt
import (
"encoding/base64"
"encoding/json"
2012-04-18 23:59:37 +04:00
"errors"
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
// 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)
2012-04-18 03:49:21 +04:00
// A JWT Token
type Token struct {
Raw string
2012-07-07 04:02:20 +04:00
Header map[string]interface{}
Claims map[string]interface{}
Method SigningMethod
2012-07-07 03:07:55 +04:00
// This is only populated when you Parse a token
2012-04-18 03:49:21 +04:00
Signature string
2012-07-07 03:12:33 +04:00
// This is only populated when you Parse/Verify a token
2012-07-07 04:02:20 +04:00
Valid bool
2012-04-18 03:49:21 +04:00
}
2012-07-07 04:02:20 +04:00
func New(method SigningMethod) *Token {
return &Token{
Header: map[string]interface{}{
"typ": "JWT",
"alg": method.Alg(),
},
Claims: make(map[string]interface{}),
2012-07-07 23:12:49 +04:00
Method: method,
}
}
2012-07-07 03:12:33 +04:00
// Get the complete, signed token
2012-07-07 04:02:20 +04:00
func (t *Token) SignedString(key []byte) (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 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 {
var source map[string]interface{}
if i == 0 {
source = t.Header
} else {
source = t.Claims
}
2012-07-07 04:02:20 +04:00
2012-07-07 03:07:55 +04:00
var jsonValue []byte
if jsonValue, err = json.Marshal(source); err != nil {
return "", err
}
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-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
func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
2012-04-18 03:49:21 +04:00
parts := strings.Split(tokenString, ".")
if len(parts) == 3 {
var err error
token := &Token{Raw: tokenString}
2012-04-18 03:49:21 +04:00
// parse Header
var headerBytes []byte
2012-04-18 23:18:31 +04:00
if headerBytes, err = DecodeSegment(parts[0]); err != nil {
2014-03-09 23:24:51 +04:00
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
2012-04-18 03:49:21 +04:00
}
if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
2014-03-09 23:24:51 +04:00
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
2012-04-18 03:49:21 +04:00
}
2012-04-18 23:59:37 +04:00
2012-04-18 03:49:21 +04:00
// parse Claims
var claimBytes []byte
2012-04-18 23:18:31 +04:00
if claimBytes, err = DecodeSegment(parts[1]); err != nil {
2014-03-09 23:24:51 +04:00
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
2012-04-18 03:49:21 +04:00
}
if err = json.Unmarshal(claimBytes, &token.Claims); err != nil {
2014-03-09 23:24:51 +04:00
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
2012-04-18 03:49:21 +04:00
}
2012-04-18 23:59:37 +04:00
2012-04-18 03:49:21 +04:00
// Lookup signature method
if method, ok := token.Header["alg"].(string); ok {
2012-07-07 23:12:49 +04:00
if token.Method = GetSigningMethod(method); token.Method == nil {
2014-03-09 23:24:51 +04:00
return token, &ValidationError{err: "Signing method (alg) is unavailable.", Errors: ValidationErrorUnverifiable}
2012-04-18 03:49:21 +04:00
}
} else {
2014-03-09 23:24:51 +04:00
return token, &ValidationError{err: "Signing method (alg) is unspecified.", Errors: ValidationErrorUnverifiable}
}
// Lookup key
var key []byte
if key, err = keyFunc(token); err != nil {
2014-03-09 23:24:51 +04:00
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorUnverifiable}
2012-04-18 03:49:21 +04:00
}
2014-02-12 10:31:34 +04:00
// Check expiration times
vErr := &ValidationError{}
2014-02-12 10:31:34 +04:00
now := TimeFunc().Unix()
2012-04-18 03:52:38 +04:00
if exp, ok := token.Claims["exp"].(float64); ok {
2014-02-12 10:31:34 +04:00
if now > int64(exp) {
vErr.err = "Token is expired"
2014-03-09 23:24:51 +04:00
vErr.Errors |= ValidationErrorExpired
2012-04-18 03:52:38 +04:00
}
}
2014-02-12 10:31:34 +04:00
if nbf, ok := token.Claims["nbf"].(float64); ok {
if now < int64(nbf) {
vErr.err = "Token is not valid yet"
2014-03-09 23:24:51 +04:00
vErr.Errors |= ValidationErrorNotValidYet
2014-02-12 10:31:34 +04:00
}
}
2012-04-18 03:49:21 +04:00
// Perform validation
if err = token.Method.Verify(strings.Join(parts[0:2], "."), parts[2], key); err != nil {
vErr.err = err.Error()
2014-03-09 23:24:51 +04:00
vErr.Errors |= ValidationErrorSignatureInvalid
2012-04-18 03:58:52 +04:00
}
2012-04-18 23:59:37 +04:00
2014-03-08 02:46:27 +04:00
if vErr.valid() {
2012-04-18 03:58:52 +04:00
token.Valid = true
return token, nil
2012-04-18 03:58:52 +04:00
}
2012-04-18 23:59:37 +04:00
return token, vErr
}
return nil, &ValidationError{err: "Token contains an invalid number of segments", Errors: ValidationErrorMalformed}
}
2014-03-09 23:26:36 +04:00
// The errors that might occur when parsing and validating a token
2014-03-09 23:24:51 +04:00
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
)
2014-03-08 02:46:27 +04:00
// The error from Parse if token is not valid
type ValidationError struct {
2014-03-09 23:24:51 +04:00
err string
Errors uint32 // bitfield. see ValidationError... constants
}
2014-03-08 02:46:27 +04:00
// Validation error is an error type
func (e ValidationError) Error() string {
if e.err == "" {
return "Token is invalid"
}
return e.err
}
// No errors
2014-03-08 02:46:27 +04:00
func (e *ValidationError) valid() bool {
2014-03-09 23:24:51 +04:00
if e.Errors > 0 {
return false
2012-04-18 03:49:21 +04:00
}
return true
2012-04-18 03:49:21 +04:00
}
2012-04-18 23:18:31 +04:00
2012-07-07 03:12:33 +04:00
// Try to find the token in an http.Request.
// 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.
func ParseFromRequest(req *http.Request, keyFunc Keyfunc) (token *Token, err error) {
2012-04-18 23:18:31 +04:00
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" {
return Parse(ah[7:], keyFunc)
}
}
2012-04-18 23:59:37 +04:00
// Look for "access_token" parameter
2012-07-07 23:40:24 +04:00
req.ParseMultipartForm(10e6)
if tokStr := req.Form.Get("access_token"); tokStr != "" {
return Parse(tokStr, keyFunc)
}
2012-04-18 23:35:16 +04:00
return nil, errors.New("No token present in request.")
2012-04-18 23:59:37 +04:00
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 {
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
}