Documentation
¶
Overview ¶
Package jwt represents JSON Web Token for Go.
Builder, all the Signers and Verifiers are safe for use by multiple goroutines simultaneously.
See [RFC 7519](https://tools.ietf.org/html/rfc7519) and see [jwt.io](https://jwt.io) for more.
Example ¶
// create a Signer (HMAC in this example) key := []byte(`secret`) signer, err := jwt.NewSignerHS(jwt.HS256, key) checkErr(err) // create claims (you can create your own, see: Example_BuildUserClaims) claims := &jwt.RegisteredClaims{ Audience: []string{"admin"}, ID: "random-unique-string", } // create a Builder builder := jwt.NewBuilder(signer) // and build a Token newToken, err := builder.Build(claims) checkErr(err) // here is token as byte slice var _ []byte = newToken.Raw() // or just token.String() for string // create a Verifier (HMAC in this example) verifier, err := jwt.NewVerifierHS(jwt.HS256, key) checkErr(err) // parse a Token (by example received from a request) tokenStr := newToken.String() token, err := jwt.ParseAndVerifyString(tokenStr, verifier) checkErr(err) // and verify it's signature err = verifier.Verify(token.Payload(), token.Signature()) checkErr(err) // also you can parse and verify together newToken, err = jwt.ParseAndVerifyString(tokenStr, verifier) checkErr(err) // get standard claims var newClaims jwt.StandardClaims errClaims := json.Unmarshal(newToken.RawClaims(), &newClaims) checkErr(errClaims) // verify claims as you var _ bool = newClaims.IsForAudience("admin") var _ bool = newClaims.IsValidAt(time.Now())
Output:
Index ¶
- Constants
- func BuildBytes(signer Signer, claims interface{}) ([]byte, error)
- type Algorithm
- type Audience
- type Builder
- type BuilderOption
- type Error
- type Header
- type NumericDate
- type RegisteredClaims
- type Signer
- func NewSignerES(alg Algorithm, key *ecdsa.PrivateKey) (Signer, error)
- func NewSignerEdDSA(key ed25519.PrivateKey) (Signer, error)
- func NewSignerHS(alg Algorithm, key []byte) (Signer, error)
- func NewSignerPS(alg Algorithm, key *rsa.PrivateKey) (Signer, error)
- func NewSignerRS(alg Algorithm, key *rsa.PrivateKey) (Signer, error)
- type StandardClaims
- func (sc *StandardClaims) IsForAudience(audience string) bool
- func (sc *StandardClaims) IsID(id string) bool
- func (sc *StandardClaims) IsIssuer(issuer string) bool
- func (sc *StandardClaims) IsSubject(subject string) bool
- func (sc *StandardClaims) IsValidAt(now time.Time) bool
- func (sc *StandardClaims) IsValidExpiresAt(now time.Time) bool
- func (sc *StandardClaims) IsValidIssuedAt(now time.Time) bool
- func (sc *StandardClaims) IsValidNotBefore(now time.Time) bool
- type Token
- type Verifier
- func NewVerifierES(alg Algorithm, key *ecdsa.PublicKey) (Verifier, error)
- func NewVerifierEdDSA(key ed25519.PublicKey) (Verifier, error)
- func NewVerifierHS(alg Algorithm, key []byte) (Verifier, error)
- func NewVerifierPS(alg Algorithm, key *rsa.PublicKey) (Verifier, error)
- func NewVerifierRS(alg Algorithm, key *rsa.PublicKey) (Verifier, error)
Examples ¶
Constants ¶
const ( // ErrNilKey indicates that key is nil. ErrNilKey = Error("jwt: key is nil") // ErrInvalidKey indicates that key is not valid. ErrInvalidKey = Error("jwt: key is not valid") // ErrUnsupportedAlg indicates that given algorithm is not supported. ErrUnsupportedAlg = Error("jwt: algorithm is not supported") // ErrInvalidFormat indicates that token format is not valid. ErrInvalidFormat = Error("jwt: token format is not valid") // ErrAudienceInvalidFormat indicates that audience format is not valid. ErrAudienceInvalidFormat = Error("jwt: audience format is not valid") // ErrDateInvalidFormat indicates that date format is not valid. ErrDateInvalidFormat = Error("jwt: date is not valid") // ErrAlgorithmMismatch indicates that token is signed by another algorithm. ErrAlgorithmMismatch = Error("jwt: token is signed by another algorithm") // ErrInvalidSignature indicates that signature is not valid. ErrInvalidSignature = Error("jwt: signature is not valid") )
Build and parse errors.
Variables ¶
This section is empty.
Functions ¶
func BuildBytes ¶
BuildBytes is used to create and encode JWT with a provided claims.
Types ¶
type Algorithm ¶
type Algorithm string
Algorithm for signing and verifying.
const ( EdDSA Algorithm = "EdDSA" HS256 Algorithm = "HS256" HS384 Algorithm = "HS384" HS512 Algorithm = "HS512" RS256 Algorithm = "RS256" RS384 Algorithm = "RS384" RS512 Algorithm = "RS512" ES256 Algorithm = "ES256" ES384 Algorithm = "ES384" ES512 Algorithm = "ES512" PS256 Algorithm = "PS256" PS384 Algorithm = "PS384" PS512 Algorithm = "PS512" )
Algorithm names for signing and verifying.
type Audience ¶
type Audience []string
Audience is a special claim that be a single string or an array of strings see RFC 7519.
func (Audience) MarshalJSON ¶
MarshalJSON implements a marshaling function for "aud" claim.
func (*Audience) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler interface.
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder is used to create a new token.
func NewBuilder ¶
func NewBuilder(signer Signer, opts ...BuilderOption) *Builder
NewBuilder returns new instance of Builder.
func (*Builder) Build ¶
Build used to create and encode JWT with a provided claims. If claims param is of type []byte or string then it's treated as a marshaled JSON. In other words you can pass already marshaled claims.
func (*Builder) BuildBytes ¶
BuildBytes used to create and encode JWT with a provided claims.
type BuilderOption ¶ added in v3.0.7
type BuilderOption func(*Builder)
BuilderOption is used to modify builder properties.
func WithContentType ¶ added in v3.0.7
func WithContentType(cty string) BuilderOption
WithContentType sets `cty` header for token.
func WithKeyID ¶ added in v3.0.7
func WithKeyID(kid string) BuilderOption
WithKeyID sets `kid` header for token.
type Header ¶
type Header struct { Algorithm Algorithm `json:"alg"` Type string `json:"typ,omitempty"` // only "JWT" can be here ContentType string `json:"cty,omitempty"` KeyID string `json:"kid,omitempty"` }
Header representa JWT header data. See: https://tools.ietf.org/html/rfc7519#section-5, https://tools.ietf.org/html/rfc7517
func (*Header) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface.
type NumericDate ¶
NumericDate represents date for StandardClaims See: https://tools.ietf.org/html/rfc7519#section-2
func NewNumericDate ¶
func NewNumericDate(t time.Time) *NumericDate
NewNumericDate creates a new NumericDate value from time.Time.
func (*NumericDate) MarshalJSON ¶
func (t *NumericDate) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface.
func (*NumericDate) UnmarshalJSON ¶
func (t *NumericDate) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface.
type RegisteredClaims ¶ added in v3.0.8
type RegisteredClaims = StandardClaims
RegisteredClaims will replace StandardClaims in v4.
type Signer ¶
Signer is used to sign tokens.
func NewSignerES ¶
func NewSignerES(alg Algorithm, key *ecdsa.PrivateKey) (Signer, error)
NewSignerES returns a new ECDSA-based signer.
func NewSignerEdDSA ¶
func NewSignerEdDSA(key ed25519.PrivateKey) (Signer, error)
NewSignerEdDSA returns a new ed25519-based signer.
func NewSignerHS ¶
NewSignerHS returns a new HMAC-based signer.
func NewSignerPS ¶
func NewSignerPS(alg Algorithm, key *rsa.PrivateKey) (Signer, error)
NewSignerPS returns a new RSA-PSS-based signer.
func NewSignerRS ¶
func NewSignerRS(alg Algorithm, key *rsa.PrivateKey) (Signer, error)
NewSignerRS returns a new RSA-based signer.
type StandardClaims ¶
type StandardClaims struct { // ID claim provides a unique identifier for the JWT. ID string `json:"jti,omitempty"` // Audience claim identifies the recipients that the JWT is intended for. Audience Audience `json:"aud,omitempty"` // Issuer claim identifies the principal that issued the JWT. // Use of this claim is OPTIONAL. Issuer string `json:"iss,omitempty"` // Subject claim identifies the principal that is the subject of the JWT. // Use of this claim is OPTIONAL. Subject string `json:"sub,omitempty"` // ExpiresAt claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. // Use of this claim is OPTIONAL. ExpiresAt *NumericDate `json:"exp,omitempty"` // IssuedAt claim identifies the time at which the JWT was issued. // This claim can be used to determine the age of the JWT. // Use of this claim is OPTIONAL. IssuedAt *NumericDate `json:"iat,omitempty"` // NotBefore claim identifies the time before which the JWT MUST NOT be accepted for processing. // Use of this claim is OPTIONAL. NotBefore *NumericDate `json:"nbf,omitempty"` }
StandardClaims represents claims for JWT. See: https://tools.ietf.org/html/rfc7519#section-4.1
func (*StandardClaims) IsForAudience ¶
func (sc *StandardClaims) IsForAudience(audience string) bool
IsForAudience reports whether token has a given audience.
func (*StandardClaims) IsID ¶
func (sc *StandardClaims) IsID(id string) bool
IsID reports whether token has a given id.
func (*StandardClaims) IsIssuer ¶
func (sc *StandardClaims) IsIssuer(issuer string) bool
IsIssuer reports whether token has a given issuer.
func (*StandardClaims) IsSubject ¶
func (sc *StandardClaims) IsSubject(subject string) bool
IsSubject reports whether token has a given subject.
func (*StandardClaims) IsValidAt ¶
func (sc *StandardClaims) IsValidAt(now time.Time) bool
IsValidAt reports whether a token is valid at a given time.
func (*StandardClaims) IsValidExpiresAt ¶
func (sc *StandardClaims) IsValidExpiresAt(now time.Time) bool
IsValidExpiresAt reports whether a token isn't expired at a given time.
func (*StandardClaims) IsValidIssuedAt ¶
func (sc *StandardClaims) IsValidIssuedAt(now time.Time) bool
IsValidIssuedAt reports whether a token was created before a given time.
func (*StandardClaims) IsValidNotBefore ¶
func (sc *StandardClaims) IsValidNotBefore(now time.Time) bool
IsValidNotBefore reports whether a token isn't used before a given time.
type Token ¶
type Token struct {
// contains filtered or unexported fields
}
Token represents a JWT token. See: https://tools.ietf.org/html/rfc7519
func Build ¶
Build is used to create and encode JWT with a provided claims.
Example ¶
key := []byte(`secret`) signer, _ := jwt.NewSignerHS(jwt.HS256, key) builder := jwt.NewBuilder(signer) claims := &jwt.RegisteredClaims{ Audience: []string{"admin"}, ID: "random-unique-string", } token, err := builder.Build(claims) checkErr(err) fmt.Printf("Algorithm %v\n", token.Header().Algorithm) fmt.Printf("Type %v\n", token.Header().Type) fmt.Printf("Claims %v\n", string(token.RawClaims())) fmt.Printf("Payload %v\n", string(token.Payload())) fmt.Printf("Token %v\n", string(token.Raw()))
Output: Algorithm HS256 Type JWT Claims {"jti":"random-unique-string","aud":"admin"} Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0 Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0.uNaqGEggmy02lZq8FM7KoUKXhOy-zrSF7inYuzIET9o
func Parse ¶
Parse decodes a token from a raw bytes.
Example ¶
rawToken := []byte(`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs`) token, err := jwt.Parse(rawToken) checkErr(err) fmt.Printf("Algorithm %v\n", token.Header().Algorithm) fmt.Printf("Type %v\n", token.Header().Type) fmt.Printf("Claims %v\n", string(token.RawClaims())) fmt.Printf("Payload %v\n", string(token.Payload())) fmt.Printf("Token %v\n", string(token.Raw()))
Output: Algorithm HS256 Type JWT Claims {"aud":"admin","jti":"random-unique-string"} Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0 Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs
func ParseAndVerify ¶
ParseAndVerify decodes a token and verifies it's signature.
Example ¶
rawToken := []byte(`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs`) key := []byte(`secret`) verifier, _ := jwt.NewVerifierHS(jwt.HS256, key) token, err := jwt.ParseAndVerify(rawToken, verifier) checkErr(err) fmt.Printf("Algorithm %v\n", token.Header().Algorithm) fmt.Printf("Type %v\n", token.Header().Type) fmt.Printf("Claims %v\n", string(token.RawClaims())) fmt.Printf("Payload %v\n", string(token.Payload())) fmt.Printf("Token %v\n", string(token.Raw()))
Output: Algorithm HS256 Type JWT Claims {"aud":"admin","jti":"random-unique-string"} Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0 Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs
func ParseAndVerifyString ¶
ParseAndVerifyString decodes a token and verifies it's signature.
func (*Token) SecureString ¶
SecureString returns token without a signature (replaced with `.<signature>`).
type Verifier ¶
Verifier is used to verify tokens.
func NewVerifierES ¶
NewVerifierES returns a new ECDSA-based verifier.
func NewVerifierEdDSA ¶
NewVerifierEdDSA returns a new ed25519-based verifier.
func NewVerifierHS ¶
NewVerifierHS returns a new HMAC-based verifier.
func NewVerifierPS ¶
NewVerifierPS returns a new RSA-PSS-based signer.