jwt (JSON Web Token for Go)

JWT Compatible

Build Status Build status GoDoc Sourcegraph


This package is a JWT signer, verifier and validator for Go (or Golang).

When it comes to JWT, there are lots of libraries available for Go. Still, I couldn't find one that was simple enough to use, so I decided to create this library in order to help whomever needs an easy solution for JWT.

The main difference between other libraries is ease of use. This library is pretty straightforward and has no external dependencies. If one is used to easy-to-use libraries, like Node's, perhaps it is the ideal library for them to use.

Also, it supports header and payload validators and all hashing algorithms (both signing and verifying).


Full documentation here.


Issue a JWT
// Set the options.
now := time.Now()
opt := &jwt.Options{
	JWTID:          "unique_id",
	Timestamp:      true,
	ExpirationTime: now.Add(24 * 30 * 12 * time.Hour),
	NotBefore:      now.Add(30 * time.Minute),
	Subject:        "123",
	Audience:       "admin",
	Issuer:         "auth_server",
	KeyID:          "my_key",
	Public:         map[string]interface{}{"foo": "bar", "myBool": true},

// Define a signer.
sig := jwt.HS256("my_53cr37")

// Issue a new token.
token, err := jwt.Sign(sig, opt)
if err != nil {
	// ...
Verify a JWT
now := time.Now()
sig := jwt.HS256("my_53cr37")
jot, err := jwt.Verify(sig)
if err != nil {
	// token is invalid
Validate a JWT
algValidator := jwt.AlgorithmValidator(jwt.MethodHS256)
expValidator := jwt.ExpirationTimeValidator(now)
audValidator := jwt.AudienceValidator("admin")
if err = jot.Validate(algValidator, expValidator, audValidator); err != nil {
	switch err {
	case jwt.ErrAlgorithmMismatch:
		// handle "alg" mismatch
	case jwt.ErrTokenExpired:
		// handle "exp" being expired
	case jwt.ErrAudienceMismatch:
		// handle "aud" mismatch


How to help:
  • Pull Requests
  • Issues
  • Opinions



    Package jwt is a JSON Web Token signer, verifier and validator.





    View Source
    const (
    	MethodHS256 = "HS256" // Method name for HMAC and SHA-256.
    	MethodHS384 = "HS384" // Method name for HMAC and SHA-384.
    	MethodHS512 = "HS512" // Method name for HMAC and SHA-512.
    	MethodRS256 = "RS256" // Method name for RSA and SHA-256.
    	MethodRS384 = "RS384" // Method name for RSA and SHA-384.
    	MethodRS512 = "RS512" // Method name for RSA and SHA-512.
    	MethodES256 = "ES256" // Method name for ECDSA and SHA-256.
    	MethodES384 = "ES384" // Method name for ECDSA and SHA-384.
    	MethodES512 = "ES512" // Method name for ECDSA and SHA-512.
    	MethodNone  = "none"  // Method name for "none".


    View Source
    var (
    	ErrNoECDSAPrivKey = errors.New("jwt.(Signer).Sign: ECDSA private key is nil")
    	ErrNoECDSAPubKey  = errors.New("jwt.(Signer).Sign: ECDSA public key is nil")
    	ErrECSDAInvalid   = errors.New("jwt.(Signer).Verify: ECDSA validation failed")
    	ErrECDSASigLen    = errors.New("jwt.(Signer).Verify: ECDSA signature has unexpected size")
    View Source
    var (
    	ErrNoHMACKey   = errors.New("jwt.(Signer).Sign: HMAC key is empty")
    	ErrHMACInvalid = errors.New("jwt.(Signer).Verify: HMAC validation failed")
    View Source
    var (
    	// ErrEmptyAuthorization indicates that the "Authorization" header
    	// doesn't have a token and, thus, extracting a token is impossible.
    	ErrEmptyAuthorization = errors.New("jwt: no token could be extracted from header")
    	// ErrMalformedToken indicates a token doesn't have
    	// a valid format, as per the RFC 7519, section 7.2.
    	ErrMalformedToken = errors.New("jwt: malformed token")
    	// ErrNilCtxKey indicates that no context key is set for retrieving
    	// JWTs from context objects. This error is resolved if a key is set.
    	ErrNilCtxKey = errors.New("jwt: JWT context key is a nil value")
    	// ErrNilCtxValue indicates the context value is nil.
    	// This mitigates possible nil pointer reference problems
    	// and avoids tiring and unnecessary JWT pointer checking.
    	ErrNilCtxValue = errors.New("jwt: context value is nil")
    	// ErrCtxAssertion indicates a JWT could not be extracted from a context object
    	// because the value it holds can not be asserted to a JWT pointer.
    	ErrCtxAssertion = errors.New("jwt: unable to assert context value into JWT pointer")
    View Source
    var (
    	ErrNoRSAPrivKey = errors.New("jwt.(Signer).Sign: RSA private key is nil")
    	ErrNoRSAPubKey  = errors.New("jwt.(Signer).Verify: RSA public key is nil")
    View Source
    var (
    	ErrAlgorithmMismatch = errors.New("jwt: Algorithm mismatch")
    	ErrAudienceMismatch  = errors.New("jwt: Audience mismatch")
    	ErrTokenExpired      = errors.New("jwt: Token expired")
    	ErrTokenFromFuture   = errors.New("jwt: Token issued at the future")
    	ErrTokenTooYoung     = errors.New("jwt: Token is not valid yet")
    	ErrIssuerMismatch    = errors.New("jwt: Issuer mismatch")
    	ErrJWTIDMismatch     = errors.New("jwt: JWTID mismatch")
    	ErrSubjectMismatch   = errors.New("jwt: Subject mismatch")
    View Source
    var ErrNoSigner = errors.New("jwt.Sign: signer is nil")


    func Sign

    func Sign(s Signer, opt *Options) (string, error)

      Sign builds a full JWT and signs its last part.



      type JWT

      type JWT struct {
      	// contains filtered or unexported fields

        JWT is a JSON Web Token.

        func FromContext

        func FromContext(ctx context.Context, key interface{}) (*JWT, error)

          FromContext extracts a JWT object from a given context.


          func FromCookie

          func FromCookie(c *http.Cookie) (*JWT, error)

            FromCookie extracts a JWT object from a given cookie.

            func FromRequest

            func FromRequest(r *http.Request) (*JWT, error)

              FromRequest builds a JWT from the token contained in the "Authorization" header.

              func FromString

              func FromString(s string) (*JWT, error)

                FromString builds a JWT from a string representation of a JSON Web Token.


                func (*JWT) Algorithm

                func (j *JWT) Algorithm() string

                  Algorithm returns the "alg" claim from the JWT's header.

                  func (*JWT) Audience

                  func (j *JWT) Audience() string

                    Audience returns the "aud" claim from the JWT's payload.

                    func (*JWT) Bytes

                    func (j *JWT) Bytes() []byte

                      Bytes returns a representation of the JWT as an array of bytes.

                      func (*JWT) ExpirationTime

                      func (j *JWT) ExpirationTime() time.Time

                        ExpirationTime returns the "exp" claim from the JWT's payload.

                        func (*JWT) ID

                        func (j *JWT) ID() string

                          ID returns the "jti" claim from the JWT's payload.

                          func (*JWT) IssuedAt

                          func (j *JWT) IssuedAt() time.Time

                            IssuedAt returns the "iat" claim from the JWT's payload.

                            func (*JWT) Issuer

                            func (j *JWT) Issuer() string

                              Issuer returns the "iss" claim from the JWT's payload.

                              func (*JWT) KeyID

                              func (j *JWT) KeyID() string

                                KeyID returns the "kid" claim from the JWT's header.

                                func (*JWT) NotBefore

                                func (j *JWT) NotBefore() time.Time

                                  NotBefore returns the "nbf" claim from the JWT's payload.

                                  func (*JWT) Public

                                  func (j *JWT) Public() map[string]interface{}

                                    Public returns all public claims set.

                                    func (*JWT) String

                                    func (j *JWT) String() string

                                    func (*JWT) Subject

                                    func (j *JWT) Subject() string

                                      Subject returns the "sub" claim from the JWT's payload.

                                      func (*JWT) Validate

                                      func (j *JWT) Validate(vfuncs ...ValidatorFunc) error

                                        Validate iterates over custom validator functions to validate the JWT.

                                        func (*JWT) Verify

                                        func (j *JWT) Verify(s Signer) error

                                          Verify verifies the Token's signature.

                                          type Options

                                          type Options struct {
                                          	JWTID          string                 // JWTID is the "jti" claim.
                                          	Timestamp      bool                   // Timestamp defines whether the JWT has the "iat" (issued at) claim set.
                                          	ExpirationTime time.Time              // ExpirationTime is the "exp" claim.
                                          	NotBefore      time.Time              // NotBefore is the "nbf" claim.
                                          	Subject        string                 // Subject is the "sub" claim.
                                          	Audience       string                 // Audience is the "aud" claim.
                                          	Issuer         string                 // Issuer is the "iss" claim.
                                          	KeyID          string                 // KeyID is the "kid" header claim.
                                          	Public         map[string]interface{} // Public is a collection of public claims that are included to the JWT's payload.

                                            Options is a set of options that defines claims that are included in a token.

                                            type Signer

                                            type Signer interface {
                                            	Sign(msg []byte) ([]byte, error)
                                            	String() string
                                            	Verify(msg, sig []byte) error

                                            func ES256

                                            func ES256(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) Signer

                                              ES256 creates a signing method using ECDSA and SHA-256.

                                              func ES384

                                              func ES384(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) Signer

                                                ES384 creates a signing method using ECDSA and SHA-384.

                                                func ES512

                                                func ES512(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) Signer

                                                  ES512 creates a signing method using ECDSA and SHA-512.

                                                  func HS256

                                                  func HS256(key string) Signer

                                                    HS256 creates a signing method using HMAC and SHA-256.

                                                    func HS384

                                                    func HS384(key string) Signer

                                                      HS384 creates a signing method using HMAC and SHA-384.

                                                      func HS512

                                                      func HS512(key string) Signer

                                                        HS512 creates a signing method using HMAC and SHA-512.

                                                        func None

                                                        func None() Signer

                                                          None returns a Signer that bypasses signing and validating, thus implementing the "none" method.

                                                          func RS256

                                                          func RS256(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer

                                                            RS256 creates a signing method using RSA and SHA-256.

                                                            func RS384

                                                            func RS384(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer

                                                              RS384 creates a signing method using RSA and SHA-384.

                                                              func RS512

                                                              func RS512(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer

                                                                RS512 creates a signing method using RSA and SHA-512.

                                                                type ValidatorFunc

                                                                type ValidatorFunc func(jot *JWT) error

                                                                  ValidatorFunc is a function for running extra validators when parsing a JWT string.

                                                                  func AlgorithmValidator

                                                                  func AlgorithmValidator(alg string) ValidatorFunc

                                                                    AlgorithmValidator validates the "alg" claim.

                                                                    func AudienceValidator

                                                                    func AudienceValidator(aud string) ValidatorFunc

                                                                      AudienceValidator validates the "aud" claim.

                                                                      func ExpirationTimeValidator

                                                                      func ExpirationTimeValidator(now time.Time) ValidatorFunc

                                                                        ExpirationTimeValidator validates the "exp" claim.

                                                                        func IDValidator

                                                                        func IDValidator(jti string) ValidatorFunc

                                                                          IDValidator validates the "jti" claim.

                                                                          func IssuedAtValidator

                                                                          func IssuedAtValidator(now time.Time) ValidatorFunc

                                                                            IssuedAtValidator validates the "iat" claim.

                                                                            func IssuerValidator

                                                                            func IssuerValidator(iss string) ValidatorFunc

                                                                              IssuerValidator validates the "iss" claim.

                                                                              func NotBeforeValidator

                                                                              func NotBeforeValidator(now time.Time) ValidatorFunc

                                                                                NotBeforeValidator validates the "nbf" claim.

                                                                                func SubjectValidator

                                                                                func SubjectValidator(sub string) ValidatorFunc

                                                                                  SubjectValidator validates the "sub" claim.