### Complete JWT Configuration and Usage Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/configuration.md Demonstrates a full JWT setup including key generation, custom claims definition, parser configuration with various options (valid methods, leeway, issuer, audience, expiration), token creation, signing, and parsing from an HTTP request. ```go import ( "time" "crypto/rand" "crypto/rsa" "github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5/request" ) // Set global precision jwt.TimePrecision = time.Millisecond jwt.MarshalSingleStringAsArray = false // Generate RSA key pair privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) publicKey := &privateKey.PublicKey // Create custom claims type AppClaims struct { jwt.RegisteredClaims UserID string `json:"user_id"` } // Create configured parser parser := jwt.NewParser( jwt.WithValidMethods([]string{"RS256"}), jwt.WithLeeway(5 * time.Second), jwt.WithIssuer("my-app"), jwt.WithAudience("my-api"), jwt.WithExpirationRequired(), ) // Create token claims := &AppClaims{ RegisteredClaims: jwt.RegisteredClaims{ Issuer: "my-app", Audience: jwt.ClaimStrings{"my-api"}, ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)), }, UserID: "user-123", } token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) tokenString, _ := token.SignedString(privateKey) // Parse from HTTP request with configuration token, err := request.ParseFromRequest( httpRequest, request.BearerExtractor{}, func(token *jwt.Token) (any, error) { return publicKey, nil }, request.WithParser(parser), request.WithClaims(&AppClaims{}), ) ``` -------------------------------- ### MultiExtractor Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/request.md Example of using MultiExtractor to first try the BearerExtractor on the Authorization header, and if that fails, try the ArgumentExtractor for 'access_token'. ```go extractor := request.MultiExtractor{ request.BearerExtractor{}, request.ArgumentExtractor{"access_token"}, } token, err := extractor.ExtractToken(httpRequest) // Tries Authorization header first, then access_token argument ``` -------------------------------- ### Install jwt-go package Source: https://github.com/golang-jwt/jwt/blob/main/README.md Use this command to add jwt-go as a dependency in your Go program. Ensure Go is installed first. ```sh go get -u github.com/golang-jwt/jwt/v5 ``` -------------------------------- ### Example MapClaims Usage Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/types.md Demonstrates creating a MapClaims instance with various standard and custom claims. ```go claims := jwt.MapClaims{ "iss": "my-app", "sub": "user-123", "aud": "my-api", "exp": float64(1234567890), "custom_claim": "custom_value", } ``` -------------------------------- ### RSA Signing and Verification Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Demonstrates how to generate an RSA key pair, sign a JWT using RS256, and verify the signature. ```go import ( "crypto/rand" "crypto/rsa" "github.com/golang-jwt/jwt/v5" ) // Generate RSA key pair (this is expensive, do once) privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { panic(err) } publicKey := &privateKey.PublicKey // Sign token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.RegisteredClaims{ Issuer: "my-app", }) tokenString, err := token.SignedString(privateKey) // Verify parsedToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { return publicKey, nil }, jwt.WithValidMethods([]string{"RS256"})) ``` -------------------------------- ### HeaderExtractor Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/request.md Example of using HeaderExtractor to try 'X-Auth-Token' and then 'Authorization' headers for token extraction. The entire header value is returned as-is. ```go // Try X-Auth-Token, then Authorization extractor := request.HeaderExtractor{"X-Auth-Token", "Authorization"} token, err := extractor.ExtractToken(httpRequest) // Header value is returned as-is // "Bearer " would be returned completely ``` -------------------------------- ### Complete JWT Validation Example with Custom Claims Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/validator.md A full example demonstrating custom claim validation, including setting leeway, issuer, audience, and expiration requirements, and validating custom claims with additional logic. ```go import ( "errors" "github.com/golang-jwt/jwt/v5" "time" ) type AppClaims struct { jwt.RegisteredClaims Permissions []string `json:"permissions"` } // Implement custom validation func (ac AppClaims) Validate() error { if len(ac.Permissions) == 0 { return errors.New("no permissions granted") } return nil } // Create validator validator := jwt.NewValidator( jwt.WithLeeway(5 * time.Second), jwt.WithIssuer("https://auth.example.com"), jwt.WithAudience("my-api"), jwt.WithExpirationRequired(), ) // Validate claims claims := &AppClaims{ RegisteredClaims: jwt.RegisteredClaims{ Issuer: "https://auth.example.com", Audience: jwt.ClaimStrings{"my-api"}, ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)), }, Permissions: []string{"read:users", "write:posts"}, } if err := validator.Validate(claims); err != nil { panic(err) } println("Claims validated successfully") ``` -------------------------------- ### ArgumentExtractor Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/request.md Example of using ArgumentExtractor to look for 'access_token' or 'token' in form data. It handles both POST bodies and URL query parameters. ```go extractor := request.ArgumentExtractor{"access_token", "token"} token, err := extractor.ExtractToken(httpRequest) // Looks for form values in POST body or URL query // Example: POST with access_token= or ?token= ``` -------------------------------- ### Example Keyfunc for Simple HMAC Secret Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/token.md Demonstrates a simple Keyfunc that returns a static secret key for HMAC signing. It includes a check to ensure the signing method is HMAC. ```go func myKeyfunc(token *jwt.Token) (any, error) { // Verify algorithm to prevent attacks if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return []byte("my-secret-key"), nil } ``` -------------------------------- ### RSA-PSS Signing and Verification Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Demonstrates how to sign a JWT using PS256 and verify the signature with RSA-PSS. ```go import ( "crypto/rand" "crypto/rsa" "github.com/golang-jwt/jwt/v5" ) privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) publicKey := &privateKey.PublicKey // Sign with PS256 token := jwt.NewWithClaims(jwt.SigningMethodPS256, jwt.RegisteredClaims{ Issuer: "my-app", }) tokenString, _ := token.SignedString(privateKey) // Verify parsedToken, _ := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { return publicKey, nil }, jwt.WithValidMethods([]string{"PS256"})) ``` -------------------------------- ### Custom Claims Validation Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/validator.md Example demonstrating how to implement the ClaimsValidator interface for a custom claims type. This includes custom validation rules for username and admin privileges. ```go import ( "errors" "github.com/golang-jwt/jwt/v5" ) // Custom claims type type MyCustomClaims struct { jwt.RegisteredClaims Username string `json:"username"` Admin bool `json:"admin"` } // Implement ClaimsValidator interface func (m MyCustomClaims) Validate() error { var errors []error // Custom validation: username required if m.Username == "" { errors = append(errors, jwt.newError( "username is required", jwt.ErrTokenInvalidClaims, )) } // Custom validation: admin must have specific issuer if m.Admin && m.Issuer != "admin-provider" { errors = append(errors, errors.New("only admin-provider can issue admin tokens")) } if len(errors) > 0 { return jwt.joinErrors(errors...) } return nil } // During parsing, Validate is automatically called token, err := jwt.ParseWithClaims( tokenString, &MyCustomClaims{}, keyFunc, jwt.WithIssuer("admin-provider"), ) if err != nil { // Error message will include custom validation failures panic(err) } ``` -------------------------------- ### PostExtractionFilter Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/request.md Example of creating a PostExtractionFilter to strip the 'Bearer ' prefix from a token extracted by the HeaderExtractor from the Authorization header. ```go // Create a filter that strips "Bearer " prefix stripBearer := func(token string) (string, error) { if len(token) > 7 && strings.EqualFold(token[:7], "bearer ") { return token[7:], nil } return token, nil } extractor := &request.PostExtractionFilter{ Extractor: request.HeaderExtractor{"Authorization"}, Filter: stripBearer, } ``` -------------------------------- ### Configure JWT Parser and Parse from Request Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/configuration.md Example demonstrating how to configure a JWT parser with specific validation methods, leeway, and issuer, and then use it to parse a token from an HTTP request with custom claims. ```go import ( "net/http" "time" "github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5/request" ) // Configure JWT parser with strict options parser := jwt.NewParser( jwt.WithValidMethods([]string{"HS256"}), jwt.WithLeeway(5 * time.Second), jwt.WithIssuer("my-app"), ) // Define custom claims type CustomClaims struct { jwt.RegisteredClaims UserID string `json:"user_id"` } // Parse from HTTP request with configuration token, err := request.ParseFromRequest( httpRequest, request.OAuth2Extractor, keyFunc, request.WithParser(parser), request.WithClaims(&CustomClaims{}), ) ``` -------------------------------- ### MapClaims Usage Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/claims.md Demonstrates parsing a JWT string into MapClaims, accessing standard and custom claims, and iterating over all claims. ```go import "github.com/golang-jwt/jwt/v5" // Parse into MapClaims (default) token, err := jwt.Parse(tokenString, keyFunc) if err != nil { panic(err) } claims := token.Claims.(jwt.MapClaims) // Access standard claims if exp, err := claims.GetExpirationTime(); err == nil && exp != nil { fmt.Println("Expires at:", exp.Time) } // Access custom claims directly username, ok := claims["username"].(string) if ok { fmt.Println("Username:", username) } // Iterate over all claims for key, value := range claims { fmt.Printf("%s: %v\n", key, value) } ``` -------------------------------- ### ECDSA Token Signing and Verification Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Demonstrates generating an ECDSA key pair, signing a JWT using ES256, and then parsing and verifying the signed token. ```go import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "github.com/golang-jwt/jwt/v5" ) // Generate ECDSA key pair privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { panic(err) } publicKey := &privateKey.PublicKey // Sign token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.RegisteredClaims{ Issuer: "my-app", }) tokenString, _ := token.SignedString(privateKey) // Verify parsedToken, _ := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { return publicKey, nil }, jwt.WithValidMethods([]string{"ES256"})) ``` -------------------------------- ### None Signing Method JWT Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Illustrates signing a JWT with the 'none' method and parsing it. Parsing fails unless the special magic constant is provided during parsing. ```go import "github.com/golang-jwt/jwt/v5" // NEVER do this in production token := jwt.NewWithClaims(jwt.SigningMethodNone, jwt.MapClaims{}) tokenString, _ := token.SignedString(jwt.UnsafeAllowNoneSignatureType) // Parsing will fail unless you explicitly allow it parsed, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { return jwt.UnsafeAllowNoneSignatureType, nil }) // If you don't pass the magic constant, parsing fails parsed2, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { return nil, nil // Fails: NoneSignatureTypeDisallowedError }) ``` -------------------------------- ### Get All Registered Algorithms Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Retrieves a list of all algorithm names that have been registered with the signing method registry. This is useful for introspection or displaying available options. ```go algs := jwt.GetAlgorithms() // algs is []string{"HS256", "HS384", "HS512", "RS256", ...} ``` -------------------------------- ### HMAC JWT Signing and Verification Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Demonstrates how to generate a secure random key, sign a JWT using HS256, and then verify the signed token. Ensure the key is cryptographically random and meets the minimum length recommendation. ```go import ( "crypto/rand" "github.com/golang-jwt/jwt/v5" ) // Generate a cryptographically random key key := make([]byte, 32) rand.Read(key) // Sign a token token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{ Issuer: "my-app", }) tokenString, err := token.SignedString(key) if err != nil { panic(err) } // Verify a token parsedToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { return key, nil }, jwt.WithValidMethods([]string{"HS256"})) ``` -------------------------------- ### Example: Standalone Validator Usage Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/validator.md Demonstrates how to create and use a standalone validator with custom options like leeway and issuer. This validator is then used to validate pre-parsed claims. ```go import "github.com/golang-jwt/jwt/v5" // Standalone validator validator := jwt.NewValidator( jwt.WithLeeway(5 * time.Second), jwt.WithIssuer("my-issuer"), ) // Validate already-parsed claims claims := &jwt.RegisteredClaims{ Issuer: "my-issuer", } err := validator.Validate(claims) if err != nil { panic(err) } ``` -------------------------------- ### Configure JWT Parser with Comprehensive Validation Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/parser-options.md This example demonstrates a comprehensive JWT parser configuration, including restricting allowed methods, requiring specific standard claims, and setting clock skew tolerance. It uses `ParseWithClaims` for detailed parsing. ```go import ( "github.com/golang-jwt/jwt/v5" "time" ) // Comprehensive parser configuration parser := jwt.NewParser( // Restrict algorithms jwt.WithValidMethods([]string{"HS256"}), // Validate standard claims jwt.WithExpirationRequired(), jwt.WithIssuer("https://auth.example.com"), jwt.WithAudience("my-api"), jwt.WithIssuedAt(), // Clock skew tolerance jwt.WithLeeway(5 * time.Second), ) token, err := parser.ParseWithClaims( tokenString, &jwt.RegisteredClaims{}, func(token *jwt.Token) (any, error) { return []byte("secret"), nil }, ) if err != nil { panic(err) } ``` -------------------------------- ### ClaimStrings Deserialization and Serialization Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/claims.md Shows how ClaimStrings deserializes from both single string and array formats for the 'aud' claim and how to control its JSON serialization behavior. ```go import "github.com/golang-jwt/jwt/v5" // Receive a token with aud claim as a single string var claims jwt.MapClaims json.Unmarshal([]byte(`{"aud":"my-app"}`), &claims) aud, _ := claims.GetAudience() // aud is ClaimStrings{"my-app"} // Receive a token with aud claim as an array json.Unmarshal([]byte(`{"aud":["app1","app2"]}`), &claims) aud, _ = claims.GetAudience() // aud is ClaimStrings{"app1", "app2"} // Control serialization behavior jwt.MarshalSingleStringAsArray = false data, _ := json.Marshal(jwt.ClaimStrings{"my-app"}) // data is `"my-app"` not `["my-app"]` ``` -------------------------------- ### Example Keyfunc for Key ID Lookup Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/token.md Shows a Keyfunc that retrieves a verification key based on the 'kid' (key ID) from the token's header. It handles missing 'kid' and unknown key IDs. ```go func myKeyfuncWithKid(token *jwt.Token) (any, error) { kid, ok := token.Header["kid"].(string) if !ok { return nil, errors.New("kid header missing") } // Lookup key by ID from your key store key := myKeyStore[kid] if key == nil { return nil, fmt.Errorf("unknown key ID: %s", kid) } return key, nil } ``` -------------------------------- ### BearerExtractor Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/request.md Example of using BearerExtractor to extract a JWT from the Authorization header. It expects the format 'Bearer ' and returns the token string without the prefix. ```go import ( "net/http" "github.com/golang-jwt/jwt/v5/request" ) extractor := request.BearerExtractor{} token, err := extractor.ExtractToken(httpRequest) if err != nil { panic(err) } // token is the JWT string without "Bearer " prefix ``` -------------------------------- ### Configure JWT Parser Options Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/configuration.md Use functional options to configure the JWT parser. This example restricts allowed signing methods, sets a leeway for time claims, requires the expiration claim, specifies an issuer, and defines an audience. ```go import ( "time" "github.com/golang-jwt/jwt/v5" ) parser := jwt.NewParser( jwt.WithValidMethods([]string{"HS256"}), jwt.WithLeeway(5 * time.Second), jwt.WithExpirationRequired(), jwt.WithIssuer("my-auth-provider"), jwt.WithAudience("my-api"), ) token, err := parser.Parse(tokenString, keyFunc) ``` -------------------------------- ### Ed25519 JWT Signing and Verification Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Demonstrates how to generate an Ed25519 key pair, sign a JWT, and then verify it using the public key. Ensure the correct key types are used for signing and verification. ```go import ( "crypto/ed25519" "crypto/rand" "github.com/golang-jwt/jwt/v5" ) // Generate Ed25519 key pair publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader) if err != nil { panic(err) } // Sign token := jwt.NewWithClaims(jwt.SigningMethodEdDSA, jwt.RegisteredClaims{ Issuer: "my-app", }) tokenString, _ := token.SignedString(privateKey) // Verify parsedToken, _ := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { return publicKey, nil }, jwt.WithValidMethods([]string{"EdDSA"})) ``` -------------------------------- ### Example: Validate Claims with Specific Requirements Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/validator.md Shows how to validate claims using a validator configured to require expiration and a specific issuer. It highlights that multiple validation errors are combined into a single error message. ```go import ( "errors" "github.com/golang-jwt/jwt/v5" ) validator := jwt.NewValidator( jwt.WithExpirationRequired(), jwt.WithIssuer("my-app"), ) claims := &jwt.RegisteredClaims{ Issuer: "my-app", } err := validator.Validate(claims) if err != nil { // Multiple validation errors are combined // Example: "token has invalid issuer, token is expired" panic(err) } ``` -------------------------------- ### Example: Marshal Single String Claim Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/types.md Demonstrates how MarshalSingleStringAsArray affects JSON output for a single string claim. The default behavior outputs an array. ```go // Default behavior jwt.MarshalSingleStringAsArray = true data, _ := json.Marshal(jwt.ClaimStrings{"my-app"}) // Output: ["my-app"] // Alternative behavior jwt.MarshalSingleStringAsArray = false data, _ := json.Marshal(jwt.ClaimStrings{"my-app"}) // Output: "my-app" ``` -------------------------------- ### Validate Audience Claim Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/validator.md Demonstrates validating the audience claim. The first example accepts tokens with at least one matching audience, while the second requires all specified audiences to be present. ```go claims := jwt.RegisteredClaims{ Audience: jwt.ClaimStrings{"my-app", "other-app"}, } // Accept either audience validator := jwt.NewValidator(jwt.WithAudience("my-app", "legacy-app")) err := validator.Validate(claims) // OK: aud contains "my-app" // Require both audiences validator2 := jwt.NewValidator(jwt.WithAllAudiences("my-app", "other-app")) err2 := validator2.Validate(claims) // OK: aud contains both ``` -------------------------------- ### Create New Token Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/token.md Use New to create a Token with a specified signing method and an empty claims map. This is a basic initialization step. ```go import "github.com/golang-jwt/jwt/v5" token := jwt.New(jwt.SigningMethodHS256) ``` -------------------------------- ### Token Parsing with VerificationKeySet Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/token.md Demonstrates how to use a Keyfunc that returns a VerificationKeySet for token parsing, enabling key rotation. ```go func myKeyfunc(token *jwt.Token) (any, error) { // Return multiple keys for key rotation return jwt.VerificationKeySet{ Keys: []jwt.VerificationKey{ currentKey, previousKey, }, }, nil } token, err := jwt.ParseWithClaims(tokenString, &jwt.RegisteredClaims{}, myKeyfunc) if err != nil { panic(err) } ``` -------------------------------- ### Combined JWT Validation Error Message Example Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/errors.md When multiple JWT validation errors occur, the library combines them into a single comma-separated string. This example shows the format of such a combined error message. ```go // Multiple errors combined: "token has invalid issuer, token is expired" ``` -------------------------------- ### Serializing NumericDate to JSON (Millisecond Precision) Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/claims.md Marshals a NumericDate to a JSON number with fractional seconds. This example demonstrates using time.Millisecond for precision. ```go // With TimePrecision = time.Millisecond jwt.TimePrecision = time.Millisecond expTime := jwt.NewNumericDate(time.Unix(1609459200, 500000000)) data, _ := json.Marshal(expTime) // data is `1609459200.5` ``` -------------------------------- ### Catching ErrInvalidKeyType Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/errors.md Check for ErrInvalidKeyType when a signing method is used with a key of an incompatible type. For example, using a string key with RSA signing. ```go if errors.Is(err, jwt.ErrInvalidKeyType) { log.Println("Key type doesn't match signing method") } ``` -------------------------------- ### Create New Parser with Options Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/parser.md Creates a new Parser instance with customizable options. Use this to configure specific validation methods and leeway for token parsing. ```go import "github.com/golang-jwt/jwt/v5" parser := jwt.NewParser( jwt.WithValidMethods([]string{"HS256"}), jwt.WithLeeway(5 * time.Second), ) ``` -------------------------------- ### WithTimeFunc Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/parser-options.md Specifies a custom function to get the current time, primarily useful for testing. This function is used instead of `time.Now()` for all time-based validations. ```APIDOC ## WithTimeFunc ### Description Specifies a custom function to get the current time. Primarily useful for testing. ### Method Signature ```go func WithTimeFunc(f func() time.Time) ParserOption ``` ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | f | func() time.Time | Function that returns the current time | ### Behavior - Used instead of time.Now() for all time-based validations - Only useful for testing with fixed or controlled time - For production clock skew, use WithLeeway instead ### Example ```go import "testing" func TestTokenExpiration(t *testing.T) { now := time.Date(2023, 1, 1, 12, 0, 0, 0, time.UTC) parser := jwt.NewParser( jwt.WithTimeFunc(func() time.Time { return now }), ) // Token exp claim will be validated against this fixed time token, _ := parser.Parse(tokenString, keyFunc) } ``` ``` -------------------------------- ### New Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/token.md Creates a new Token with the specified signing method and an empty map of claims. This is useful for creating tokens where claims will be added later. ```APIDOC ## New ### Description Creates a new Token with the specified signing method and an empty map of claims. ### Method func New(method SigningMethod, opts ...TokenOption) *Token ### Parameters #### Path Parameters - **method** (SigningMethod) - Required - The signing method to use for this token (e.g., jwt.SigningMethodHS256) - **opts** (...TokenOption) - Optional - Additional token options (currently unused but reserved for future use) ### Returns A new Token struct with the method set and an empty MapClaims object. ### Example ```go import "github.com/golang-jwt/jwt/v5" token := jwt.New(jwt.SigningMethodHS256) ``` ``` -------------------------------- ### Serializing NumericDate to JSON (Default Precision) Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/claims.md Marshals a NumericDate to a JSON number representing seconds since the UNIX epoch. This example uses the default time precision (time.Second). ```go // With TimePrecision = time.Second (default) expTime := jwt.NewNumericDate(time.Unix(1609459200, 0)) data, _ := json.Marshal(expTime) // data is `1609459200` ``` -------------------------------- ### Pre-registered RSA Signing Method Instances Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Provides pre-registered instances for common RSA signing methods like RS256, RS384, and RS512. ```go var ( SigningMethodRS256 *SigningMethodRSA SigningMethodRS384 *SigningMethodRSA SigningMethodRS512 *SigningMethodRSA ) ``` -------------------------------- ### Pre-registered RSA-PSS Signing Method Instances Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Provides pre-registered instances for RSA-PSS signing methods like PS256, PS384, and PS512. ```go var ( SigningMethodPS256 *SigningMethodRSAPSS SigningMethodPS384 *SigningMethodRSAPSS SigningMethodPS512 *SigningMethodRSAPSS ) ``` -------------------------------- ### Instantiate JWT Validator with Options in Go Source: https://github.com/golang-jwt/jwt/blob/main/MIGRATION_GUIDE.md Demonstrates how to create a JWT Validator instance with custom options, such as setting a leeway for time-based claims. This allows for independent validation of claims outside the token parsing process. ```go var v = jwt.NewValidator(jwt.WithLeeway(5*time.Second)) v.Validate(myClaims) ``` -------------------------------- ### Pre-registered HMAC Signing Method Instances Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Provides pre-registered instances for common HMAC signing methods (HS256, HS384, HS512) that are automatically available. ```go var ( SigningMethodHS256 *SigningMethodHMAC SigningMethodHS384 *SigningMethodHMAC SigningMethodHS512 *SigningMethodHMAC ) ``` -------------------------------- ### Validate Claims with Specific Requirements and Handle Errors Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/validator.md Create a validator with required issuer and audience, and expiration. Demonstrates how to validate claims and check for specific errors using errors.Is. ```go import ( "errors" "github.com/golang-jwt/jwt/v5" ) validator := jwt.NewValidator( jwt.WithExpirationRequired(), jwt.WithIssuer("my-issuer"), jwt.WithAudience("my-app"), ) claims := jwt.RegisteredClaims{ Issuer: "wrong-issuer", } err := validator.Validate(claims) if err != nil { // Error message: "token has invalid issuer, exp claim is required, token has invalid audience" // Check for specific errors using errors.Is if errors.Is(err, jwt.ErrTokenExpired) { println("Token expired") } if errors.Is(err, jwt.ErrTokenInvalidIssuer) { println("Invalid issuer") } } ``` -------------------------------- ### GetAlgorithms Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Fetches a list of all algorithm names that have been registered with the signing method registry. ```APIDOC ## GetAlgorithms ### Description Returns a list of all registered algorithm names. ### Method Signature ```go func GetAlgorithms() (algs []string) ``` ### Returns - **algs** ([]string) - A slice of algorithm identifiers. ### Request Example ```go algs := jwt.GetAlgorithms() // algs is []string{"HS256", "HS384", "HS512", "RS256", ...} ``` ``` -------------------------------- ### Configure JWT Parser with Options Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/request.md Use WithParser to provide a pre-configured jwt.Parser. This allows setting valid methods, leeway, and issuer validation. ```go import ( "time" "github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5/request" ) parser := jwt.NewParser( jwt.WithValidMethods([]string{"HS256"}), jwt.WithLeeway(5 * time.Second), jwt.WithIssuer("my-app"), ) token, err := request.ParseFromRequest( httpRequest, request.OAuth2Extractor, keyFunc, request.WithParser(parser), ) ``` -------------------------------- ### NewParser Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/parser.md Creates a new Parser instance with configurable options. Allows setting valid signing methods, leeway for time-based claims, and other behaviors. ```APIDOC ## NewParser ### Description Creates a new Parser with the specified options. ### Signature ```go func NewParser(options ...ParserOption) *Parser ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | ...ParserOption | no | — | Variable number of parser options to configure behavior | ### Returns A configured Parser instance. ### Example ```go import "github.com/golang-jwt/jwt/v5" parser := jwt.NewParser( jwt.WithValidMethods([]string{"HS256"}), jwt.WithLeeway(5 * time.Second), ) ``` ``` -------------------------------- ### Pre-registered ECDSA Signing Method Instances Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Provides pre-registered instances for common ECDSA signing methods: ES256 (P-256, SHA-256), ES384 (P-384, SHA-384), and ES512 (P-521, SHA-512). ```go var ( SigningMethodES256 *SigningMethodECDSA // P-256 curve, SHA-256 SigningMethodES384 *SigningMethodECDSA // P-384 curve, SHA-384 SigningMethodES512 *SigningMethodECDSA // P-521 curve, SHA-512 ) ``` -------------------------------- ### Create New Token with Claims Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/token.md Use NewWithClaims to create a Token with a specific signing method and custom claims. This is the primary method for token creation with data. ```go import "github.com/golang-jwt/jwt/v5" claims := jwt.RegisteredClaims{ Issuer: "my-app", Subject: "user-123", } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) ``` -------------------------------- ### Configure JWT Parser with Base64 Options Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/configuration.md Instantiate a new JWT parser with options to control base64 encoding behavior. Use WithPaddingAllowed() for non-standard padding or WithStrictDecoding() for strict RFC 4648 compliance. ```go // Allow padding (non-standard) parser := jwt.NewParser(jwt.WithPaddingAllowed()) // Strict RFC 4648 compliance parser := jwt.NewParser(jwt.WithStrictDecoding()) ``` -------------------------------- ### Parse JWT Token with Default Configuration Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/parser.md Use this function to parse a JWT token string with the default configuration. It requires the token string, a key function to provide the verification key, and optional parser options. ```go func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) ``` ```go token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { return []byte("secret"), nil }, jwt.WithValidMethods([]string{"HS256"})) ``` -------------------------------- ### None Signing Method Definition Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Defines the 'none' signing method as per RFC 7519. This method should not be used in production environments. ```go var SigningMethodNone *signingMethodNone ``` -------------------------------- ### RSA Signing Method Definition Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Defines the structure for RSA signing methods, including the name and hash algorithm. ```go type SigningMethodRSA struct { Name string Hash crypto.Hash } ``` -------------------------------- ### Catching ErrTokenUnverifiable Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/errors.md Shows how to catch the ErrTokenUnverifiable error, which indicates issues like an unknown signing algorithm, a missing key function, or disallowed use of the 'none' algorithm. ```Go package main import ( "log" "time" "github.com/golang-jwt/jwt/v5" ) func main() { tokenString := "eyJhbGciOiJVTk5PV04iLCJ0eXAiOiJKV1QifQ.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKK9_H4.E.E" claims := jwt.MapClaims{} parser := jwt.NewParser() _, err := parser.ParseUnverified(tokenString, claims) // Using ParseUnverified for demonstration if errors.Is(err, jwt.ErrTokenUnverifiable) { log.Println("Cannot verify token signature: signing method unavailable or other verification issue.") } else if err != nil { log.Fatalf("An unexpected error occurred: %v", err) } } ``` -------------------------------- ### Import jwt-go in Go code Source: https://github.com/golang-jwt/jwt/blob/main/README.md Import the jwt package into your Go source files to use its functionalities. ```go import "github.com/golang-jwt/jwt/v5" ``` -------------------------------- ### Generate and Use RSA Key Pair Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/configuration.md Generate an RSA key pair with a minimum of 2048 bits. The private key is used for signing, and the public key for verification. ```go import ( "crypto/rand" "crypto/rsa" ) // Generate key pair privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) publicKey := &privateKey.PublicKey // Use in token signing token.SignedString(privateKey) // Use in verification parser.Parse(tokenString, func(token *jwt.Token) (any, error) { return publicKey, nil }) ``` -------------------------------- ### NewWithClaims Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/token.md Creates a new Token with the specified signing method and claims. This is the primary way to create a token with custom claims. ```APIDOC ## NewWithClaims ### Description Creates a new Token with the specified signing method and claims. This is the primary way to create a token with custom claims. ### Method func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *Token ### Parameters #### Path Parameters - **method** (SigningMethod) - Required - The signing method to use for this token - **claims** (Claims) - Required - The claims object to embed in the token (implements Claims interface) - **opts** (...TokenOption) - Optional - Additional token options (currently unused) ### Returns A new Token struct with the specified claims and signing method. ### Example ```go import "github.com/golang-jwt/jwt/v5" claims := jwt.RegisteredClaims{ Issuer: "my-app", Subject: "user-123", } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) ``` ``` -------------------------------- ### None Signing Method Security Constant Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Defines the magic constant required to allow the 'none' signing method. This is a security measure to prevent accidental acceptance of unsigned tokens. ```go const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" var NoneSignatureTypeDisallowedError error ``` -------------------------------- ### SigningMethod Interface Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/types.md Interface that signing method implementations must follow. It defines methods for verification, signing, and algorithm identification. ```go type SigningMethod interface { Verify(signingString string, sig []byte, key any) error Sign(signingString string, key any) ([]byte, error) Alg() string } ``` -------------------------------- ### SigningMethodRSA Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Implements the RSA family of signing methods using PKCS#1 v1.5 padding. Expects `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for verification. ```APIDOC ## SigningMethodRSA ### Description Implements the RSA family of signing methods using PKCS#1 v1.5 padding. Expects `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for verification. ### Key Requirements - **Signing:** `*rsa.PrivateKey` (minimum 2048 bits recommended) - **Verification:** `*rsa.PublicKey` extracted from private key ### Example ```go import ( "crypto/rand" "crypto/rsa" "github.com/golang-jwt/jwt/v5" ) // Generate RSA key pair (this is expensive, do once) privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { panic(err) } publicKey := &privateKey.PublicKey // Sign token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.RegisteredClaims{ Issuer: "my-app", }) tokenString, err := token.SignedString(privateKey) // Verify parsedToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { return publicKey, nil }, jwt.WithValidMethods([]string{"RS256"})) ``` ``` -------------------------------- ### Pre-registered Ed25519 Instance Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Provides a pre-registered instance for the EdDSA signing method using Ed25519 keys. ```go var SigningMethodEdDSA *SigningMethodEd25519 ``` -------------------------------- ### Retrieve Registered Signing Method Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Retrieves a signing method instance by its algorithm identifier. It's important to check if the returned method is nil, indicating that the algorithm is not registered. ```go method := jwt.GetSigningMethod("HS256") if method == nil { panic("HS256 not registered") } ``` -------------------------------- ### Catching Not Valid Yet Token Error Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/errors.md Shows how to validate claims with a 'not before' time and catch the ErrTokenNotValidYet error if the current time is before the specified time. ```go claims := jwt.RegisteredClaims{ NotBefore: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)), } validator := jwt.NewValidator() er := validator.Validate(claims) // Error: ErrTokenNotValidYet ``` ```go if errors.Is(err, jwt.ErrTokenNotValidYet) { log.Println("Token will become valid in the future, try again later") } ``` -------------------------------- ### Golang JWT Module Structure Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/README.md Overview of the main components and their functionalities within the golang-jwt/jwt library. ```go github.com/golang-jwt/jwt/v5 ├── Token (token creation and signing) ├── Claims interface (standard and custom claims) ├── Parser (token parsing) ├── Validator (claims validation) ├── SigningMethod interface (algorithm implementations) └── request subpackage (HTTP request extraction) ├── Extractor interface (token extraction strategies) ├── ParseFromRequest (parse from HTTP request) └── Pre-built extractors (OAuth2, Bearer, etc.) ``` -------------------------------- ### SigningMethodNone Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Implements the "none" signing method as required by RFC 7519. This method should **never** be used in production. It requires a special magic constant `UnsafeAllowNoneSignatureType` for security. ```APIDOC ## SigningMethodNone ### Description Implements the "none" signing method as required by RFC 7519. This should **never** be used in production. ### Security To prevent accidental acceptance of unsigned tokens, the "none" method requires the special magic constant `UnsafeAllowNoneSignatureType` as the key. ### Example ```go import "github.com/golang-jwt/jwt/v5" // NEVER do this in production token := jwt.NewWithClaims(jwt.SigningMethodNone, jwt.MapClaims{}) tokenString, _ := token.SignedString(jwt.UnsafeAllowNoneSignatureType) // Parsing will fail unless you explicitly allow it parsed, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { return jwt.UnsafeAllowNoneSignatureType, nil }) // If you don't pass the magic constant, parsing fails parsed2, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { return nil, nil // Fails: NoneSignatureTypeDisallowedError }) ``` ``` -------------------------------- ### Create and Sign JWT Token Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/README.md Creates a new JWT token with registered claims and signs it using the HS256 algorithm with a provided secret key. ```go import "github.com/golang-jwt/jwt/v5" claims := jwt.RegisteredClaims{ Issuer: "my-app", } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) tokenString, err := token.SignedString([]byte("secret")) ``` -------------------------------- ### Create JWT Validator Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/configuration.md Instantiate a new JWT validator with custom parser options. All ParserOption functions that apply to the Parser also apply to the Validator. ```go validator := jwt.NewValidator(opts...ParserOption) ``` -------------------------------- ### Ed25519 Signing Method Definition Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Defines the Ed25519 signing method. It expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification. ```go type SigningMethodEd25519 struct{} ``` -------------------------------- ### RSA-PSS Signing Method Definition Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Defines the structure for RSA-PSS signing methods, extending RSA methods with PSS-specific options. ```go type SigningMethodRSAPSS struct { *SigningMethodRSA Options *rsa.PSSOptions VerifyOptions *rsa.PSSOptions } ``` -------------------------------- ### GetSubject Method Signature Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/claims.md Provides the method signature for retrieving the subject claim (sub). ```go func (c Claims) GetSubject() (string, error) ``` -------------------------------- ### VerificationKeySet Structure Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/token.md Defines the structure for a set of verification keys. ```go type VerificationKeySet struct { Keys []VerificationKey } ``` -------------------------------- ### Register Custom Signing Method Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/configuration.md Define and register a custom signing method with a unique algorithm name. This involves implementing the jwt.SigningMethod interface. ```go import "github.com/golang-jwt/jwt/v5" type CustomMethod struct{} func (m *CustomMethod) Alg() string { return "CUSTOM" } func (m *CustomMethod) Verify(signingString string, sig []byte, key any) error { // Custom verification return nil } func (m *CustomMethod) Sign(signingString string, key any) ([]byte, error) { // Custom signing return []byte{}, nil } // Register during init func init() { jwt.RegisterSigningMethod("CUSTOM", func() jwt.SigningMethod { return &CustomMethod{} }) } ``` -------------------------------- ### Register Custom Signing Method Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Registers a custom signing method with a unique algorithm name. The factory function provided should return an instance of your custom SigningMethod implementation. ```go import "github.com/golang-jwt/jwt/v5" type MySigningMethod struct{} func (m *MySigningMethod) Alg() string { return "CUSTOM" } func (m *MySigningMethod) Verify(signingString string, sig []byte, key any) error { // Custom verification logic return nil } func (m *MySigningMethod) Sign(signingString string, key any) ([]byte, error) { // Custom signing logic return []byte{}, nil } // Register during init func init() { jwt.RegisterSigningMethod("CUSTOM", func() jwt.SigningMethod { return &MySigningMethod{} }) } ``` -------------------------------- ### Signing Methods Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/README.md Instances of various signing methods available for JWTs. ```APIDOC ## SigningMethod Instances ### Description Pre-defined instances for common JWT signing algorithms. ### Available Methods: - SigningMethodHS256, SigningMethodHS384, SigningMethodHS512 - SigningMethodRS256, SigningMethodRS384, SigningMethodRS512 - SigningMethodPS256, SigningMethodPS384, SigningMethodPS512 - SigningMethodES256, SigningMethodES384, SigningMethodES512 - SigningMethodEdDSA - SigningMethodNone ``` -------------------------------- ### GetSigningMethod Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/signing-methods.md Retrieves a pre-registered signing method using its algorithm name. ```APIDOC ## GetSigningMethod ### Description Retrieves a registered signing method by algorithm name. ### Method Signature ```go func GetSigningMethod(alg string) (method SigningMethod) ``` ### Parameters #### Path Parameters - **alg** (string) - Required - The algorithm identifier ### Returns - **method** (SigningMethod) - The SigningMethod instance, or nil if not found. ### Request Example ```go method := jwt.GetSigningMethod("HS256") if method == nil { panic("HS256 not registered") } ``` ``` -------------------------------- ### GetExpirationTime Method Signature Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/claims.md Provides the method signature for retrieving the expiration time claim (exp). ```go func (c Claims) GetExpirationTime() (*NumericDate, error) ``` -------------------------------- ### Create Standalone Validator Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/api-reference/validator.md Creates a new Validator instance with specified options. Typically used for validating claims outside of the standard token parsing flow. ```go func NewValidator(opts ...ParserOption) *Validator ``` -------------------------------- ### Token Creation Source: https://github.com/golang-jwt/jwt/blob/main/_autodocs/README.md Functions for creating new JWT tokens, with or without pre-defined claims. ```APIDOC ## New() ### Description Creates a new JWT token with an empty claims set. ### Method `New()` ### Parameters None ### Response - **Token** (*Token) - A new JWT token object. ## NewWithClaims(claims Claims) ### Description Creates a new JWT token with the provided claims. ### Method `NewWithClaims(claims Claims)` ### Parameters - **claims** (Claims) - The claims to include in the token. ### Response - **Token** (*Token) - A new JWT token object. ```