Documentation
¶
Overview ¶
Package jwt is a JSON Web Token signer, verifier and validator.
Example ¶
package main import ( "fmt" "net/http" "net/http/httptest" "time" "github.com/gbrlsnchs/jwt" ) func main() { // Timestamp the exact moment this function runs // for validating purposes. now := time.Now() // Mock an HTTP request for showing off token extraction. w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/", nil) // Build JWT from the incoming request. jot, err := jwt.FromRequest(r) if err != nil { // Handle malformed token... } if err = jot.Verify(jwt.HS256("secret")); err != nil { // Handle verification error... } // Define validators for validating the JWT. If desired, there // could be custom validators too, e.g. to validate public claims. algValidator := jwt.AlgorithmValidator(jwt.MethodHS256) audValidator := jwt.AudienceValidator("test") expValidator := jwt.ExpirationTimeValidator(now) if err = jot.Validate(algValidator, audValidator, expValidator); err != nil { switch err { case jwt.ErrAlgorithmMismatch: // Handle "alg" mismatch... case jwt.ErrAudienceMismatch: // Handle "aud" mismatch... case jwt.ErrTokenExpired: // Handle "exp" being expired... } } // "Sign" issues a raw string, but if desired, one could also // use "FromString" method to have a JWT object. token, err := jwt.Sign(jwt.HS256("secret"), &jwt.Options{Timestamp: true}) if err != nil { // ... } auth := fmt.Sprintf("Bearer %s", token) w.Header().Set("Authorization", auth) w.WriteHeader(http.StatusOK) w.Write([]byte(token)) }
Output:
Index ¶
- Constants
- Variables
- func Sign(s Signer, opt *Options) (string, error)
- type JWT
- func (j *JWT) Algorithm() string
- func (j *JWT) Audience() string
- func (j *JWT) Bytes() []byte
- func (j *JWT) ExpirationTime() time.Time
- func (j *JWT) ID() string
- func (j *JWT) IssuedAt() time.Time
- func (j *JWT) Issuer() string
- func (j *JWT) KeyID() string
- func (j *JWT) NotBefore() time.Time
- func (j *JWT) Public() map[string]interface{}
- func (j *JWT) String() string
- func (j *JWT) Subject() string
- func (j *JWT) Validate(vfuncs ...ValidatorFunc) error
- func (j *JWT) Verify(s Signer) error
- type Options
- type Signer
- func ES256(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) Signer
- func ES384(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) Signer
- func ES512(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) Signer
- func HS256(key string) Signer
- func HS384(key string) Signer
- func HS512(key string) Signer
- func None() Signer
- func RS256(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer
- func RS384(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer
- func RS512(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer
- type ValidatorFunc
- func AlgorithmValidator(alg string) ValidatorFunc
- func AudienceValidator(aud string) ValidatorFunc
- func ExpirationTimeValidator(now time.Time) ValidatorFunc
- func IDValidator(jti string) ValidatorFunc
- func IssuedAtValidator(now time.Time) ValidatorFunc
- func IssuerValidator(iss string) ValidatorFunc
- func NotBeforeValidator(now time.Time) ValidatorFunc
- func SubjectValidator(sub string) ValidatorFunc
Examples ¶
Constants ¶
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". )
Variables ¶
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") )
var ( ErrNoHMACKey = errors.New("jwt.(Signer).Sign: HMAC key is empty") ErrHMACInvalid = errors.New("jwt.(Signer).Verify: HMAC validation failed") )
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") )
var ( ErrNoRSAPrivKey = errors.New("jwt.(Signer).Sign: RSA private key is nil") ErrNoRSAPubKey = errors.New("jwt.(Signer).Verify: RSA public key is nil") )
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") )
var ErrNoSigner = errors.New("jwt.Sign: signer is nil")
Functions ¶
func Sign ¶
Sign builds a full JWT and signs its last part.
Example ¶
package main import ( "fmt" "time" "github.com/gbrlsnchs/jwt" ) func main() { nextYear := time.Now().Add(24 * 30 * 12 * time.Hour) token, err := jwt.Sign(jwt.HS256("secret"), &jwt.Options{ExpirationTime: nextYear}) if err != nil { // ... } fmt.Println(token) }
Output:
Types ¶
type JWT ¶
type JWT struct {
// contains filtered or unexported fields
}
JWT is a JSON Web Token.
func FromContext ¶ added in v0.5.0
FromContext extracts a JWT object from a given context.
Example ¶
package main import ( "context" "fmt" "github.com/gbrlsnchs/jwt" ) func main() { jot, err := jwt.FromString("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M") if err != nil { // Handle malformed token... } key := "JWT" ctx := context.WithValue(context.Background(), key, jot) jot, err = jwt.FromContext(ctx, key) if err != nil { // Handle JWT absence from context... } fmt.Println(jot) }
Output:
func FromCookie ¶ added in v0.5.0
FromCookie extracts a JWT object from a given cookie.
func FromRequest ¶ added in v0.3.0
FromRequest builds a JWT from the token contained in the "Authorization" header.
func FromString ¶ added in v0.4.0
FromString builds a JWT from a string representation of a JSON Web Token.
Example ¶
package main import ( "fmt" "github.com/gbrlsnchs/jwt" ) func main() { jot, err := jwt.FromString("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M") if err != nil { // Handle malformed token... } if err = jot.Verify(jwt.HS256("secret")); err != nil { // Handle verification error... } fmt.Println(jot) }
Output:
func (*JWT) ExpirationTime ¶ added in v0.3.0
ExpirationTime returns the "exp" claim from the JWT's payload.
func (*JWT) Validate ¶ added in v0.4.0
func (j *JWT) Validate(vfuncs ...ValidatorFunc) error
Validate iterates over custom validator functions to validate the JWT.
type Options ¶ added in v0.3.0
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 ¶ added in v0.3.0
type Signer interface { Sign(msg []byte) ([]byte, error) String() string Verify(msg, sig []byte) error }
func ES256 ¶ added in v0.3.0
func ES256(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) Signer
ES256 creates a signing method using ECDSA and SHA-256.
func ES384 ¶ added in v0.3.0
func ES384(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) Signer
ES384 creates a signing method using ECDSA and SHA-384.
func ES512 ¶ added in v0.3.0
func ES512(priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey) Signer
ES512 creates a signing method using ECDSA and SHA-512.
func None ¶ added in v0.4.0
func None() Signer
None returns a Signer that bypasses signing and validating, thus implementing the "none" method.
func RS256 ¶ added in v0.3.0
func RS256(priv *rsa.PrivateKey, pub *rsa.PublicKey) Signer
RS256 creates a signing method using RSA and SHA-256.
type ValidatorFunc ¶ added in v0.4.0
ValidatorFunc is a function for running extra validators when parsing a JWT string.
func AlgorithmValidator ¶ added in v0.4.0
func AlgorithmValidator(alg string) ValidatorFunc
AlgorithmValidator validates the "alg" claim.
func AudienceValidator ¶ added in v0.4.0
func AudienceValidator(aud string) ValidatorFunc
AudienceValidator validates the "aud" claim.
func ExpirationTimeValidator ¶ added in v0.4.0
func ExpirationTimeValidator(now time.Time) ValidatorFunc
ExpirationTimeValidator validates the "exp" claim.
func IDValidator ¶ added in v0.4.0
func IDValidator(jti string) ValidatorFunc
IDValidator validates the "jti" claim.
func IssuedAtValidator ¶ added in v0.4.0
func IssuedAtValidator(now time.Time) ValidatorFunc
IssuedAtValidator validates the "iat" claim.
func IssuerValidator ¶ added in v0.4.0
func IssuerValidator(iss string) ValidatorFunc
IssuerValidator validates the "iss" claim.
func NotBeforeValidator ¶ added in v0.4.0
func NotBeforeValidator(now time.Time) ValidatorFunc
NotBeforeValidator validates the "nbf" claim.
func SubjectValidator ¶ added in v0.4.0
func SubjectValidator(sub string) ValidatorFunc
SubjectValidator validates the "sub" claim.