jwt-go: github.com/dgrijalva/jwt-go Index | Examples | Files | Directories

package jwt

import "github.com/dgrijalva/jwt-go"

Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html

See README.md for more info.

Code:

// See func authHandler for an example auth handler that produces a token
res, err := http.PostForm(fmt.Sprintf("http://localhost:%v/authenticate", serverPort), url.Values{
    "user": {"test"},
    "pass": {"known"},
})
if err != nil {
    fatal(err)
}

if res.StatusCode != 200 {
    fmt.Println("Unexpected status code", res.StatusCode)
}

// Read the token out of the response body
buf := new(bytes.Buffer)
io.Copy(buf, res.Body)
res.Body.Close()
tokenString := strings.TrimSpace(buf.String())

// Parse the token
token, err := jwt.ParseWithClaims(tokenString, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) {
    // since we only use the one private key to sign the tokens,
    // we also only use its public counter part to verify
    return verifyKey, nil
})
fatal(err)

claims := token.Claims.(*CustomClaimsExample)
fmt.Println(claims.CustomerInfo.Name)

Output:

test

Code:

// Make a sample token
// In a real world situation, this token will have been acquired from
// some other API call (see Example_getTokenViaHTTP)
token, err := createToken("foo")
fatal(err)

// Make request.  See func restrictedHandler for example request processor
req, err := http.NewRequest("GET", fmt.Sprintf("http://localhost:%v/restricted", serverPort), nil)
fatal(err)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token))
res, err := http.DefaultClient.Do(req)
fatal(err)

// Read the response body
buf := new(bytes.Buffer)
io.Copy(buf, res.Body)
res.Body.Close()
fmt.Println(buf.String())

Output:

Welcome, foo

Index

Examples

Package Files

claims.go doc.go ecdsa.go ecdsa_utils.go errors.go hmac.go map_claims.go none.go parser.go rsa.go rsa_pss.go rsa_utils.go signing_method.go token.go

Constants

const (
    ValidationErrorMalformed        uint32 = 1 << iota // Token is malformed
    ValidationErrorUnverifiable                        // Token could not be verified because of signing problems
    ValidationErrorSignatureInvalid                    // Signature validation failed

    // Standard Claim validation errors
    ValidationErrorAudience      // AUD validation failed
    ValidationErrorExpired       // EXP validation failed
    ValidationErrorIssuedAt      // IAT validation failed
    ValidationErrorIssuer        // ISS validation failed
    ValidationErrorNotValidYet   // NBF validation failed
    ValidationErrorId            // JTI validation failed
    ValidationErrorClaimsInvalid // Generic claims validation error
)

The errors that might occur when parsing and validating a token

const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed"

Variables

var (
    ErrNotECPublicKey  = errors.New("Key is not a valid ECDSA public key")
    ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key")
)
var (
    ErrInvalidKey      = errors.New("key is invalid")
    ErrInvalidKeyType  = errors.New("key is of invalid type")
    ErrHashUnavailable = errors.New("the requested hash function is unavailable")
)

Error constants

var (
    ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
    ErrNotRSAPrivateKey    = errors.New("Key is not a valid RSA private key")
    ErrNotRSAPublicKey     = errors.New("Key is not a valid RSA public key")
)
var (
    // Sadly this is missing from crypto/ecdsa compared to crypto/rsa
    ErrECDSAVerification = errors.New("crypto/ecdsa: verification error")
)
var NoneSignatureTypeDisallowedError error
var SigningMethodNone *signingMethodNone

Implements the none signing method. This is required by the spec but you probably should never use it.

var TimeFunc = time.Now

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.

func DecodeSegment Uses

func DecodeSegment(seg string) ([]byte, error)

Decode JWT specific base64url encoding with padding stripped

func EncodeSegment Uses

func EncodeSegment(seg []byte) string

Encode JWT specific base64url encoding with padding stripped

func ParseECPrivateKeyFromPEM Uses

func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error)

Parse PEM encoded Elliptic Curve Private Key Structure

func ParseECPublicKeyFromPEM Uses

func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error)

Parse PEM encoded PKCS1 or PKCS8 public key

func ParseRSAPrivateKeyFromPEM Uses

func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)

Parse PEM encoded PKCS1 or PKCS8 private key

func ParseRSAPublicKeyFromPEM Uses

func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)

Parse PEM encoded PKCS1 or PKCS8 public key

func RegisterSigningMethod Uses

func RegisterSigningMethod(alg string, f func() SigningMethod)

Register the "alg" name and a factory function for signing method. This is typically done during init() in the method's implementation

type Claims Uses

type Claims interface {
    Valid() error
}

For a type to be a Claims object, it must just have a Valid method that determines if the token is invalid for any supported reason

type Keyfunc Uses

type Keyfunc func(*Token) (interface{}, error)

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 properties in the Header of the token (such as `kid`) to identify which key to use.

type MapClaims Uses

type MapClaims map[string]interface{}

Claims type that uses the map[string]interface{} for JSON decoding This is the default claims type if you don't supply one

func (MapClaims) Valid Uses

func (m MapClaims) Valid() error

Validates time based claims "exp, iat, nbf". There is no accounting for clock skew. As well, if any of the above claims are not in the token, it will still be considered a valid claim.

func (MapClaims) VerifyAudience Uses

func (m MapClaims) VerifyAudience(cmp string, req bool) bool

Compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset

func (MapClaims) VerifyExpiresAt Uses

func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool

Compares the exp claim against cmp. If required is false, this method will return true if the value matches or is unset

func (MapClaims) VerifyIssuedAt Uses

func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool

Compares the iat claim against cmp. If required is false, this method will return true if the value matches or is unset

func (MapClaims) VerifyIssuer Uses

func (m MapClaims) VerifyIssuer(cmp string, req bool) bool

Compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset

func (MapClaims) VerifyNotBefore Uses

func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool

Compares the nbf claim against cmp. If required is false, this method will return true if the value matches or is unset

type Parser Uses

type Parser struct {
    ValidMethods         []string // If populated, only these methods will be considered valid
    UseJSONNumber        bool     // Use JSON Number format in JSON decoder
    SkipClaimsValidation bool     // Skip claims validation during token parsing
}

func (*Parser) Parse Uses

func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error)

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 (*Parser) ParseWithClaims Uses

func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error)

type SigningMethod Uses

type SigningMethod interface {
    Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid
    Sign(signingString string, key interface{}) (string, error)    // Returns encoded signature or error
    Alg() string                                                   // returns the alg identifier for this method (example: 'HS256')
}

Implement SigningMethod to add new methods for signing or verifying tokens.

func GetSigningMethod Uses

func GetSigningMethod(alg string) (method SigningMethod)

Get a signing method from an "alg" string

type SigningMethodECDSA Uses

type SigningMethodECDSA struct {
    Name      string
    Hash      crypto.Hash
    KeySize   int
    CurveBits int
}

Implements the ECDSA family of signing methods signing methods

var (
    SigningMethodES256 *SigningMethodECDSA
    SigningMethodES384 *SigningMethodECDSA
    SigningMethodES512 *SigningMethodECDSA
)

Specific instances for EC256 and company

func (*SigningMethodECDSA) Alg Uses

func (m *SigningMethodECDSA) Alg() string

func (*SigningMethodECDSA) Sign Uses

func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error)

Implements the Sign method from SigningMethod For this signing method, key must be an ecdsa.PrivateKey struct

func (*SigningMethodECDSA) Verify Uses

func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error

Implements the Verify method from SigningMethod For this verify method, key must be an ecdsa.PublicKey struct

type SigningMethodHMAC Uses

type SigningMethodHMAC struct {
    Name string
    Hash crypto.Hash
}

Implements the HMAC-SHA family of signing methods signing methods

var (
    SigningMethodHS256  *SigningMethodHMAC
    SigningMethodHS384  *SigningMethodHMAC
    SigningMethodHS512  *SigningMethodHMAC
    ErrSignatureInvalid = errors.New("signature is invalid")
)

Specific instances for HS256 and company

func (*SigningMethodHMAC) Alg Uses

func (m *SigningMethodHMAC) Alg() string

func (*SigningMethodHMAC) Sign Uses

func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error)

Implements the Sign method from SigningMethod for this signing method. Key must be []byte

func (*SigningMethodHMAC) Verify Uses

func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error

Verify the signature of HSXXX tokens. Returns nil if the signature is valid.

type SigningMethodRSA Uses

type SigningMethodRSA struct {
    Name string
    Hash crypto.Hash
}

Implements the RSA family of signing methods signing methods

var (
    SigningMethodRS256 *SigningMethodRSA
    SigningMethodRS384 *SigningMethodRSA
    SigningMethodRS512 *SigningMethodRSA
)

Specific instances for RS256 and company

func (*SigningMethodRSA) Alg Uses

func (m *SigningMethodRSA) Alg() string

func (*SigningMethodRSA) Sign Uses

func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error)

Implements the Sign method from SigningMethod For this signing method, must be an rsa.PrivateKey structure.

func (*SigningMethodRSA) Verify Uses

func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error

Implements the Verify method from SigningMethod For this signing method, must be an rsa.PublicKey structure.

type SigningMethodRSAPSS Uses

type SigningMethodRSAPSS struct {
    *SigningMethodRSA
    Options *rsa.PSSOptions
}

Implements the RSAPSS family of signing methods signing methods

var (
    SigningMethodPS256 *SigningMethodRSAPSS
    SigningMethodPS384 *SigningMethodRSAPSS
    SigningMethodPS512 *SigningMethodRSAPSS
)

Specific instances for RS/PS and company

func (*SigningMethodRSAPSS) Sign Uses

func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error)

Implements the Sign method from SigningMethod For this signing method, key must be an rsa.PrivateKey struct

func (*SigningMethodRSAPSS) Verify Uses

func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error

Implements the Verify method from SigningMethod For this verify method, key must be an rsa.PublicKey struct

type StandardClaims Uses

type StandardClaims struct {
    Audience  string `json:"aud,omitempty"`
    ExpiresAt int64  `json:"exp,omitempty"`
    Id        string `json:"jti,omitempty"`
    IssuedAt  int64  `json:"iat,omitempty"`
    Issuer    string `json:"iss,omitempty"`
    NotBefore int64  `json:"nbf,omitempty"`
    Subject   string `json:"sub,omitempty"`
}

Structured version of Claims Section, as referenced at https://tools.ietf.org/html/rfc7519#section-4.1 See examples for how to use this with your own claim types

func (StandardClaims) Valid Uses

func (c StandardClaims) Valid() error

Validates time based claims "exp, iat, nbf". There is no accounting for clock skew. As well, if any of the above claims are not in the token, it will still be considered a valid claim.

func (*StandardClaims) VerifyAudience Uses

func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool

Compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset

func (*StandardClaims) VerifyExpiresAt Uses

func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool

Compares the exp claim against cmp. If required is false, this method will return true if the value matches or is unset

func (*StandardClaims) VerifyIssuedAt Uses

func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool

Compares the iat claim against cmp. If required is false, this method will return true if the value matches or is unset

func (*StandardClaims) VerifyIssuer Uses

func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool

Compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset

func (*StandardClaims) VerifyNotBefore Uses

func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool

Compares the nbf claim against cmp. If required is false, this method will return true if the value matches or is unset

type Token Uses

type Token struct {
    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    Claims                 // 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
}

A JWT Token. Different fields will be used depending on whether you're creating or parsing/verifying a token.

func New Uses

func New(method SigningMethod) *Token

Create a new Token. Takes a signing method

Example creating, signing, and encoding a JWT token using the HMAC signing method

Code:

// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
    "foo": "bar",
    "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
})

// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString(hmacSampleSecret)

fmt.Println(tokenString, err)

Output:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU <nil>

func NewWithClaims Uses

func NewWithClaims(method SigningMethod, claims Claims) *Token

Example creating a token using a custom claims type. The StandardClaim is embedded in the custom type to allow for easy encoding, parsing and validation of standard claims.

Code:

mySigningKey := []byte("AllYourBase")

type MyCustomClaims struct {
    Foo string `json:"foo"`
    jwt.StandardClaims
}

// Create the Claims
claims := MyCustomClaims{
    "bar",
    jwt.StandardClaims{
        ExpiresAt: 15000,
        Issuer:    "test",
    },
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString(mySigningKey)
fmt.Printf("%v %v", ss, err)

Output:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c <nil>

Example (atypical) using the StandardClaims type by itself to parse a token. The StandardClaims type is designed to be embedded into your custom types to provide standard validation features. You can use it alone, but there's no way to retrieve other fields after parsing. See the CustomClaimsType example for intended usage.

Code:

mySigningKey := []byte("AllYourBase")

// Create the Claims
claims := &jwt.StandardClaims{
    ExpiresAt: 15000,
    Issuer:    "test",
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString(mySigningKey)
fmt.Printf("%v %v", ss, err)

Output:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.QsODzZu3lUZMVdhbO76u3Jv02iYCvEHcYVUI1kOWEU0 <nil>

func Parse Uses

func Parse(tokenString string, keyFunc Keyfunc) (*Token, error)

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

An example of parsing the error types using bitfield checks

Code:

// Token from another example.  This token is expired
var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
    return []byte("AllYourBase"), nil
})

if token.Valid {
    fmt.Println("You look nice today")
} else if ve, ok := err.(*jwt.ValidationError); ok {
    if ve.Errors&jwt.ValidationErrorMalformed != 0 {
        fmt.Println("That's not even a token")
    } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
        // Token is either expired or not active yet
        fmt.Println("Timing is everything")
    } else {
        fmt.Println("Couldn't handle this token:", err)
    }
} else {
    fmt.Println("Couldn't handle this token:", err)
}

Output:

Timing is everything

Example parsing and validating a token using the HMAC signing method

Code:

// sample token string taken from the New example
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU"

// Parse takes the token string and a function for looking up the key. The latter is especially
// useful if you use multiple keys for your application.  The standard is to use 'kid' in the
// head of the token to identify which key to use, but the parsed token (head and claims) is provided
// to the callback, providing flexibility.
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
    // Don't forget to validate the alg is what you expect:
    if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
        return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
    }

    // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
    return hmacSampleSecret, nil
})

if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
    fmt.Println(claims["foo"], claims["nbf"])
} else {
    fmt.Println(err)
}

Output:

bar 1.4444784e+09

func ParseWithClaims Uses

func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error)

Example creating a token using a custom claims type. The StandardClaim is embedded in the custom type to allow for easy encoding, parsing and validation of standard claims.

Code:

tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"

type MyCustomClaims struct {
    Foo string `json:"foo"`
    jwt.StandardClaims
}

// sample token is expired.  override time so it parses as valid
at(time.Unix(0, 0), func() {
    token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
        return []byte("AllYourBase"), nil
    })

    if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
        fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt)
    } else {
        fmt.Println(err)
    }
})

Output:

bar 15000

func (*Token) SignedString Uses

func (t *Token) SignedString(key interface{}) (string, error)

Get the complete, signed token

func (*Token) SigningString Uses

func (t *Token) SigningString() (string, error)

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.

type ValidationError Uses

type ValidationError struct {
    Inner  error  // stores the error returned by external dependencies, i.e.: KeyFunc
    Errors uint32 // bitfield.  see ValidationError... constants
    // contains filtered or unexported fields
}

The error from Parse if token is not valid

func NewValidationError Uses

func NewValidationError(errorText string, errorFlags uint32) *ValidationError

Helper for constructing a ValidationError with a string error message

func (ValidationError) Error Uses

func (e ValidationError) Error() string

Validation error is an error type

Directories

PathSynopsis
requestUtility package for extracting JWT tokens from HTTP requests.

Package jwt imports 17 packages (graph) and is imported by 1343 packages. Updated 2017-11-20. Refresh now. Tools for package owners.