### Install jwt v5 Source: https://github.com/cristalhq/jwt/blob/main/README.md Install the latest version of the jwt library using go get. Requires Go version 1.17+. ```bash go get github.com/cristalhq/jwt/v5 ``` -------------------------------- ### ErrUnsupportedAlg Example Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/errors.md Illustrates handling ErrUnsupportedAlg, which occurs when an unsupported algorithm identifier is used with signer or verifier constructors. Examples include using HMAC algorithms with RSA constructors or undefined algorithm strings. ```Go var ErrUnsupportedAlg = errors.New("algorithm is not supported") ``` ```Go // Using RS256 algorithm with HMAC constructor _, err := jwt.NewSignerHS(jwt.RS256, []byte("secret")) if err == jwt.ErrUnsupportedAlg { fmt.Println("HS256/HS384/HS512 are the supported HMAC algorithms") } // Using undefined algorithm string _, err = jwt.NewSignerRS(jwt.Algorithm("INVALID"), privateKey) if err == jwt.ErrUnsupportedAlg { fmt.Println("Algorithm not supported") } ``` -------------------------------- ### Example Usage of NewNumericDate Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/utility-types.md Demonstrates creating NumericDate instances for expiration and not-before times using the NewNumericDate function. ```go now := time.Now() expiresAt := jwt.NewNumericDate(now.Add(1 * time.Hour)) notBefore := jwt.NewNumericDate(now.Add(5 * time.Minute)) ``` -------------------------------- ### Create NumericDate with Claims Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/utility-types.md Example of creating NumericDate instances for expiration, issuance, and not-before times and assigning them to RegisteredClaims. ```go expiresAt := jwt.NewNumericDate(time.Now().Add(24 * time.Hour)) issuedAt := jwt.NewNumericDate(time.Now()) notBefore := jwt.NewNumericDate(time.Now().Add(5 * time.Minute)) claims := &jwt.RegisteredClaims{ ExpiresAt: expiresAt, IssuedAt: issuedAt, NotBefore: notBefore, } ``` -------------------------------- ### ErrNilKey Example Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/errors.md Demonstrates checking for ErrNilKey when creating signers or verifiers with empty or nil keys. This error occurs when cryptographic keys are not properly provided. ```Go var ErrNilKey = errors.New("key is nil") ``` ```Go _, err := jwt.NewSignerHS(jwt.HS256, []byte{}) if err == jwt.ErrNilKey { fmt.Println("Key cannot be empty") } _, err = jwt.NewSignerRS(jwt.RS256, nil) if err == jwt.ErrNilKey { fmt.Println("Private key cannot be nil") } ``` -------------------------------- ### Example Usage of JWT Header Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/utility-types.md Demonstrates how to build a JWT token and access its header information, including algorithm, type, content type, and key ID. ```go signer, _ := jwt.NewSignerHS(jwt.HS256, []byte("secret")) builder := jwt.NewBuilder(signer, jwt.WithKeyID("2024-key"), jwt.WithContentType("application/jwt"), ) claims := &jwt.RegisteredClaims{} token, _ := builder.Build(claims) header := token.Header() fmt.Println(header.Algorithm) // HS256 fmt.Println(header.Type) // JWT fmt.Println(header.ContentType) // application/jwt fmt.Println(header.KeyID) // 2024-key ``` -------------------------------- ### Creating and Signing RegisteredClaims Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/claims.md Example demonstrating how to create a RegisteredClaims object, set its fields including expiration and issuance times, and then sign it using HS256 algorithm. ```go expiresAt := jwt.NewNumericDate(time.Now().Add(24 * time.Hour)) claims := &jwt.RegisteredClaims{ ID: "token-id-12345", Audience: jwt.Audience{"api", "admin-panel"}, Issuer: "auth-server", Subject: "user-789", ExpiresAt: expiresAt, IssuedAt: jwt.NewNumericDate(time.Now()), NotBefore: jwt.NewNumericDate(time.Now()), } signer, _ := jwt.NewSignerHS(jwt.HS256, []byte("secret")) builder := jwt.NewBuilder(signer) token, _ := builder.Build(claims) ``` -------------------------------- ### Example Usage of JWT Audience Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/utility-types.md Shows how to create and check JWT claims with single or multiple audiences using the Audience type. ```go // Single audience claims := &jwt.RegisteredClaims{ Audience: jwt.Audience{"api"}, } // Multiple audiences claims := &jwt.RegisteredClaims{ Audience: jwt.Audience{"api", "admin-panel", "reports"}, } // Usage check if claims.IsForAudience("admin-panel") { fmt.Println("Token is for admin panel") } ``` -------------------------------- ### Configure JWT Builder with Custom Headers Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/configuration.md Example of creating a JWT builder with custom header fields like KeyID and ContentType. This is useful for access tokens or when using key rotation. ```go builder := jwt.NewBuilder(signer, jwt.WithKeyID("2024-rotating-key-1"), jwt.WithContentType("application/at+jwt"), // For access tokens ) // The header will contain: // { // "alg": "HS256", // "typ": "JWT", // "cty": "application/at+jwt", // "kid": "2024-rotating-key-1" // } ``` -------------------------------- ### JWT Error Handling Examples Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/README.md Demonstrates how to handle common JWT-related errors using a switch statement. This covers scenarios like nil keys, unsupported algorithms, invalid token formats, signature mismatches, and claim validation failures. ```Go switch err { case jwt.ErrNilKey: // Key is empty or nil case jwt.ErrUnsupportedAlg: // Algorithm not supported case jwt.ErrInvalidFormat: // Token format is malformed case jwt.ErrAlgorithmMismatch: // Token algorithm doesn't match verifier case jwt.ErrInvalidSignature: // Signature verification failed case jwt.ErrAudienceInvalidFormat: // Invalid audience claim format case jwt.ErrDateInvalidFormat: // Invalid numeric date format default: // Other errors } ``` -------------------------------- ### ErrInvalidKey Example Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/errors.md Shows how to handle ErrInvalidKey, which is returned when a provided key fails validation checks for specific algorithms. This includes curve mismatches for ECDSA and incorrect byte lengths for Ed25519. ```Go var ErrInvalidKey = errors.New("key is not valid") ``` ```Go import "crypto/ecdsa" import "crypto/elliptic" // Generate P-256 key but try to use with ES384 privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) _, err := jwt.NewSignerES(jwt.ES384, privateKey) if err == jwt.ErrInvalidKey { fmt.Println("Key curve does not match algorithm") } // Ed25519 key must be exactly 64 bytes invalidKey := make([]byte, 63) _, err = jwt.NewSignerEdDSA(invalidKey) if err == jwt.ErrInvalidKey { fmt.Println("Ed25519 private key must be 64 bytes") } ``` -------------------------------- ### Get Token as String Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/token.md Returns the complete JWT token as a string in the standard `header.claims.signature` format. Useful for displaying or transmitting the token. ```Go token, err := jwt.Parse(tokenBytes, verifier) if err != nil { log.Fatal(err) } tokenString := token.String() fmt.Println(tokenString) // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` -------------------------------- ### ErrNotJWTType Example Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/errors.md This error variable, ErrNotJWTType, is present for backward compatibility but is no longer actively used in the library. ```Go var ErrNotJWTType = errors.New("token of not JWT type") ``` -------------------------------- ### Get Raw Signature Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/token.md Returns the raw, decoded signature bytes of the token. Useful for verification or analysis purposes. ```Go signature := token.Signature() fmt.Printf("Signature length: %d bytes\n", len(signature)) ``` -------------------------------- ### Example of MarshalJSON for NumericDate Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/utility-types.md Shows how NumericDate is marshaled into a JSON numeric timestamp within RegisteredClaims. The output is a JSON string representing seconds since epoch. ```go expiresAt := jwt.NewNumericDate(time.Date(2024, 12, 31, 23, 59, 59, 0, time.UTC)) claims := &jwt.RegisteredClaims{ ExpiresAt: expiresAt, } jsonBytes, _ := json.Marshal(claims) // jsonBytes contains: {"exp":1735689599} ``` -------------------------------- ### Concurrent-Safe JWT Building Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/README.md Demonstrates how to safely use the JWT builder concurrently across multiple goroutines. Ensure the signer and builder are initialized before starting concurrent operations. ```go signer, _ := jwt.NewSignerHS(jwt.HS256, []byte("secret")) builder := jwt.NewBuilder(signer) // Safe to call from multiple goroutines simultaneously var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(1) go func(id int) { defer wg.Done() claims := &jwt.RegisteredClaims{Subject: fmt.Sprintf("user-%d", id)} token, _ := builder.Build(claims) // Use token... }(i) } wg.Wait() ``` -------------------------------- ### Get Algorithm Type Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/rsa-pss-signer.md Retrieves the specific RSA-PSS algorithm (PS256, PS384, or PS512) used by the PSAlg instance. ```go privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) signer, _ := jwt.NewSignerPS(jwt.PS256, privateKey) fmt.Println(signer.Algorithm()) // PS256 ``` -------------------------------- ### Get Token as Bytes Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/token.md Returns the complete JWT token as a byte slice in the standard JWT format. Useful when byte-level manipulation or storage is required. ```Go token, err := jwt.Parse(tokenBytes, verifier) if err != nil { log.Fatal(err) } tokenBytes := token.Bytes() ``` -------------------------------- ### Example of UnmarshalJSON for NumericDate Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/utility-types.md Demonstrates unmarshaling a JSON string containing a numeric timestamp into RegisteredClaims. The numeric value is converted back to a Unix timestamp. ```go jsonStr := `{"exp":1735689599}` var claims jwt.RegisteredClaims err := json.Unmarshal([]byte(jsonStr), &claims) if err != nil { log.Fatal(err) } fmt.Println(claims.ExpiresAt.Unix()) // 1735689599 ``` -------------------------------- ### ErrInvalidFormat Examples Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/errors.md Demonstrates checks for ErrInvalidFormat, returned when a token has an invalid structure, such as missing parts, invalid base64url encoding, or malformed JSON headers. This error is crucial for validating incoming JWTs. ```Go var ErrInvalidFormat = errors.New("token format is not valid") ``` ```Go // Missing a part _, err := jwt.Parse([]byte("header.claims"), verifier) if err == jwt.ErrInvalidFormat { fmt.Println("Token must have 3 parts separated by dots") } // Invalid base64url _, err = jwt.Parse([]byte("header..signature"), verifier) if err == jwt.ErrInvalidFormat { fmt.Println("Token format is invalid") } // Doesn't look like JWT _, err = jwt.Parse([]byte("not-a-jwt"), verifier) if err == jwt.ErrInvalidFormat { fmt.Println("Token doesn't start with eyJ") } ``` -------------------------------- ### RegisteredClaims.IsValidNotBefore Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/claims.md Checks if the token's validity period has started, ensuring it is not used before its designated start time. ```APIDOC ## RegisteredClaims.IsValidNotBefore(now time.Time) ### Description Reports whether the token is not yet used before the given time. ### Method Signature ```go func (sc *RegisteredClaims) IsValidNotBefore(now time.Time) bool ``` ### Parameters #### Path Parameters - **now** (time.Time) - Required - The time to check against ### Return Type `bool` - Returns true if NotBefore is not set or is before the given time, false otherwise. ### Example ```go var claims jwt.RegisteredClaims token.DecodeClaims(&claims) if claims.IsValidNotBefore(time.Now()) { fmt.Println("Token usage window has started") } else { fmt.Println("Token cannot be used yet") } ``` ``` -------------------------------- ### Handle ErrUninitializedToken Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/errors.md Demonstrates the incorrect manual token creation and how to correctly handle ErrUninitializedToken by ensuring tokens are parsed via Parse() or ParseNoVerify(). ```go // This should not happen in normal usage token := &jwt.Token{} // Incorrect: should use Parse() verifier, _ := jwt.NewVerifierHS(jwt.HS256, []byte("secret")) err := verifier.Verify(token) if err == jwt.ErrUninitializedToken { fmt.Println("Token must be created via Parse() or ParseNoVerify()") } // Correct way: tokenBytes := []byte("eyJ...") // Valid token parsedToken, err := jwt.Parse(tokenBytes, verifier) if err != nil { log.Fatal(err) } err = verifier.Verify(parsedToken) // This works ``` -------------------------------- ### Get EdDSA Signature Size Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/eddsa-signer.md Returns the fixed signature size in bytes for ed25519, which is always 64. ```go func (ed *EdDSAAlg) SignSize() int ``` ```go _, privateKey, _ := ed25519.GenerateKey(rand.Reader) signer, _ := jwt.NewSignerEdDSA(privateKey) fmt.Println(signer.SignSize()) // 64 ``` -------------------------------- ### JWT Signing and Verification Flow Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/README.md Illustrates the typical steps for creating, signing, and verifying JWT tokens using the package. This involves creating a signer, building a token with claims, creating a verifier, parsing the token, and decoding claims. ```Go 1. **Create signer** — Choose algorithm and provide key 2. **Build token** — Use Builder with claims 3. **Create verifier** — Same algorithm with public/shared key 4. **Parse token** — Verify signature automatically 5. **Decode claims** — Extract and validate claim values ``` -------------------------------- ### Get EdDSA Algorithm Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/eddsa-signer.md Retrieves the algorithm identifier for the EdDSAAlg instance. This method always returns EdDSA. ```go func (ed *EdDSAAlg) Algorithm() Algorithm ``` ```go _, privateKey, _ := ed25519.GenerateKey(rand.Reader) signer, _ := jwt.NewSignerEdDSA(privateKey) fmt.Println(signer.Algorithm()) // EdDSA ``` -------------------------------- ### Create and Verify JWT with RSA Keys Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/README.md Demonstrates token creation and verification using RSA keys (RS256). Requires generating an RSA key pair. ```go package main import ( "crypto/rand" "crypto/rsa" "log" "github.com/cristalhq/jwt/v5" ) func main() { // Generate RSA key pair privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { log.Fatal(err) } publicKey := &privateKey.PublicKey // Create signer with RSA signer, err := jwt.NewSignerRS(jwt.RS256, privateKey) if err != nil { log.Fatal(err) } // Create and sign token builder := jwt.NewBuilder(signer) claims := &jwt.RegisteredClaims{ Subject: "user-123", } token, err := builder.Build(claims) if err != nil { log.Fatal(err) } // Create verifier with public key verifier, err := jwt.NewVerifierRS(jwt.RS256, publicKey) if err != nil { log.Fatal(err) } // Verify token _, err = jwt.Parse(token.Bytes(), verifier) if err != nil { log.Fatal("Verification failed:", err) } } ``` -------------------------------- ### Get Payload Part Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/token.md Retrieves the combined base64url-encoded header and claims portion of the token. This is the part of the token that was signed. ```Go payloadPart := token.PayloadPart() // payloadPart = []byte("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0") ``` -------------------------------- ### Get Signature Size Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/rsa-pss-signer.md Returns the expected size in bytes for an RSA-PSS signature, which corresponds to the RSA key size. ```go privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) signer, _ := jwt.NewSignerPS(jwt.PS256, privateKey) fmt.Println(signer.SignSize()) // 256 ``` -------------------------------- ### Create New HMAC Verifier (Go) Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/hmac-signer.md Creates a new HMAC-based verifier with the specified algorithm and secret key. The key must match the one used for signing. Handles potential errors like nil keys or unsupported algorithms. ```go key := []byte("my-secret-key") verifier, err := jwt.NewVerifierHS(jwt.HS256, key) if err != nil { log.Fatal(err) } tokenBytes := []byte("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...") token, err := jwt.Parse(tokenBytes, verifier) if err != nil { log.Fatal(err) } fmt.Println("Token verified successfully") ``` -------------------------------- ### Get Signature Part Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/token.md Retrieves the base64url-encoded signature portion of the token. This is the last part of the JWT string, after the second dot. ```Go signaturePart := token.SignaturePart() // signaturePart = []byte("uNaqGEggmy02lZq8FM7KoUKXhOy-zrSF7inYuzIET9o") ``` -------------------------------- ### Configure JWT Builder with Options Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/configuration.md Use this snippet to create a JWT builder with custom Key ID and Content Type header parameters. Ensure a signer is created before initializing the builder. ```go import ( "time" "github.com/cristalhq/jwt/v5" ) // Create signer key := []byte("my-secret-key") signer, err := jwt.NewSignerHS(jwt.HS256, key) if err != nil { log.Fatal(err) } // Create builder with options builder := jwt.NewBuilder(signer, jwt.WithKeyID("current-key-version-1"), jwt.WithContentType("application/jwt"), ) // Create claims claims := &jwt.RegisteredClaims{ ID: "token-unique-id", Subject: "user-123", Audience: jwt.Audience{"api", "admin"}, Issuer: "auth-service", ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)), IssuedAt: jwt.NewNumericDate(time.Now()), NotBefore: jwt.NewNumericDate(time.Now()), } // Build token token, err := builder.Build(claims) if err != nil { log.Fatal(err) } // Verify header header := token.Header() fmt.Println(header.Algorithm) // HS256 fmt.Println(header.KeyID) // current-key-version-1 fmt.Println(header.ContentType) // application/jwt ``` -------------------------------- ### Get Claims Part Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/token.md Retrieves the base64url-encoded claims portion of the token. This is the middle part of the JWT string, between the two dots. ```Go claimsPart := token.ClaimsPart() // claimsPart = []byte("eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0") ``` -------------------------------- ### Get Header Part Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/token.md Retrieves the base64url-encoded header portion of the token. This is the first part of the JWT string, before the first dot. ```Go headerPart := token.HeaderPart() // headerPart = []byte("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9") ``` -------------------------------- ### Create New JWT Builder Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/builder.md Instantiate a new Builder with a signer and optional header configurations. ```go func NewBuilder(signer Signer, opts ...BuilderOption) *Builder ``` ```go key := []byte("secret") signer, err := jwt.NewSignerHS(jwt.HS256, key) if err != nil { log.Fatal(err) } // Create a basic builder builder := jwt.NewBuilder(signer) // Create a builder with options builder := jwt.NewBuilder(signer, jwt.WithKeyID("2024-key-1"), jwt.WithContentType("application/jwt"), ) ``` -------------------------------- ### Configure RSA Signer and Verifier Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/configuration.md Use for RSA-based algorithms like RS256, RS384, RS512. Requires a 2048-bit RSA private key for signing and a public key for verification. ```go import ( "crypto/rand" "crypto/rsa" ) // Generate 2048-bit RSA key pair privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) publicKey := &privateKey.PublicKey // Create signer and verifier signer, _ := jwt.NewSignerRS(jwt.RS256, privateKey) verifier, _ := jwt.NewVerifierRS(jwt.RS256, publicKey) ``` -------------------------------- ### BuilderOption Functions Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/builder.md Functions to configure the Builder, such as setting Key ID or Content Type. ```APIDOC ## BuilderOption Functions ### WithKeyID #### Description Returns a BuilderOption that sets the Key ID (`kid`) header claim. #### Method `WithKeyID` #### Parameters - **kid** (string) - Required - The Key ID value to set in the JWT header. #### Example ```go builder := jwt.NewBuilder(signer, jwt.WithKeyID("2024-primary")) ``` ### WithContentType #### Description Returns a BuilderOption that sets the Content Type (`cty`) header claim. #### Method `WithContentType` #### Parameters - **cty** (string) - Required - The Content Type value to set in the JWT header. #### Example ```go builder := jwt.NewBuilder(signer, jwt.WithContentType("application/jwt")) ``` ``` -------------------------------- ### Builder.Build Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/builder.md Constructs and signs a JWT token with the provided claims. The claims can be a struct, byte slice, or string. ```APIDOC ## Builder.Build ### Description Constructs and signs a JWT token with the provided claims. The claims can be a struct (which will be JSON-marshaled), a `[]byte` slice, or a `string` (treated as pre-marshaled JSON). ### Method `Build` ### Parameters #### Arguments - **claims** (any) - Required - Claims data. Can be a struct (will be JSON-marshaled), `[]byte`, or `string` (treated as pre-marshaled JSON). ### Return type `(*Token, error)` - Returns a signed Token on success, or an error if signing fails. ### Throws/Rejects - Returns error if the signer fails. - Returns error if claims cannot be JSON-marshaled (when claims is a struct). ### Example ```go key := []byte("secret") signer, _ := jwt.NewSignerHS(jwt.HS256, key) builder := jwt.NewBuilder(signer) // Using RegisteredClaims struct claims := &jwt.RegisteredClaims{ Audience: []string{"admin"}, ID: "unique-id-123", } token, err := builder.Build(claims) if err != nil { log.Fatal(err) } fmt.Println(token.String()) // Using custom struct type customClaims struct { UserID string `json:"user_id"` Role string `json:"role"` } claims2 := &customClaims{ UserID: "user-42", Role: "admin", } token2, err := builder.Build(claims2) if err != nil { log.Fatal(err) } // Using pre-marshaled JSON bytes claimsJSON := []byte(`{"user_id":"user-42","role":"admin"}`) token3, err := builder.Build(claimsJSON) if err != nil { log.Fatal(err) } // Using JSON string claimsString := `{"user_id":"user-42","role":"admin"}` token4, err := builder.Build(claimsString) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Signer.SignSize() Method Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/signer-verifier.md Returns the expected size in bytes of the signature produced by this signer. Useful for pre-allocating buffers. ```go func (s Signer) SignSize() int ``` -------------------------------- ### Verifier Interface Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/signer-verifier.md The Verifier interface defines the methods required for any JWT verification algorithm implementation. It includes methods to get the algorithm and to verify a token. ```APIDOC ## Verifier Interface The `Verifier` interface defines methods that any verification algorithm implementation must provide. ### Verifier.Algorithm() Returns the algorithm identifier used by this verifier. **Return type:** `Algorithm` - The algorithm identifier (e.g., `HS256`, `RS256`, `ES256`, `PS256`, `EdDSA`). ### Verifier.Verify(token *Token) Verifies the token's signature. #### Parameters - **token** (*Token) - Required - The parsed Token to verify **Return type:** `error` - Returns nil if verification succeeds, or an error if verification fails. **Possible errors:** - `ErrUninitializedToken` - If token was not created via Parse function - `ErrAlgorithmMismatch` - If token algorithm does not match verifier algorithm - `ErrInvalidSignature` - If signature verification fails - Other algorithm-specific errors ``` -------------------------------- ### Build and Sign JWT Token Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/builder.md Constructs and signs a JWT token using the builder. Supports various claim formats including structs, byte slices, and strings. ```go func (b *Builder) Build(claims any) (*Token, error) ``` ```go key := []byte("secret") signer, _ := jwt.NewSignerHS(jwt.HS256, key) builder := jwt.NewBuilder(signer) // Using RegisteredClaims struct claims := &jwt.RegisteredClaims{ Audience: []string{"admin"}, ID: "unique-id-123", } token, err := builder.Build(claims) if err != nil { log.Fatal(err) } fmt.Println(token.String()) // Using custom struct type customClaims struct { UserID string `json:"user_id"` Role string `json:"role"` } claims2 := &customClaims{ UserID: "user-42", Role: "admin", } token2, err := builder.Build(claims2) if err != nil { log.Fatal(err) } // Using pre-marshaled JSON bytes claimsJSON := []byte(`{"user_id":"user-42","role":"admin"}`) token3, err := builder.Build(claimsJSON) if err != nil { log.Fatal(err) } // Using JSON string claimsString := `{"user_id":"user-42","role":"admin"}` token4, err := builder.Build(claimsString) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Utility Types and Functions Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/MANIFEST.txt Documentation for utility types like Header, Audience, and NumericDate, and utility functions for generating random bits and creating numeric dates. ```APIDOC ## Utility Types and Functions ### Description Provides essential utility types and functions for JWT manipulation, including data structures for headers and dates, and helper functions. ### Utility Types - **Header**: Represents the JWT header, containing fields like `alg`, `typ`, `kid`, `cty`. - **Audience**: Represents the `aud` claim, supporting marshaling and unmarshaling. - **NumericDate**: Represents JWT dates as seconds since epoch (Unix time), with methods for manipulation. - **MarshalJSON()**: Marshals the `NumericDate` to JSON. - **UnmarshalJSON(data []byte)**: Unmarshals JSON data into a `NumericDate`. ### Utility Functions - **GenerateRandomBits(n int)**: Generates a byte slice of `n` random bits. - **NewNumericDate(t time.Time)**: Creates a new `NumericDate` from a `time.Time` object. ``` -------------------------------- ### Token Methods Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/MANIFEST.txt Documentation for the Token type and its associated methods, including string and byte conversions, accessing parts of the token, and decoding claims. ```APIDOC ## Token Methods ### Description Provides methods for interacting with JWT tokens, including conversion to string and byte representations, and accessing individual parts of the token (header, claims, payload, signature). ### Methods - **String()**: Returns the token as a compact JWS string. - **Bytes()**: Returns the token as a byte slice. - **HeaderPart()**: Returns the base64-encoded header part. - **ClaimsPart()**: Returns the base64-encoded claims part. - **PayloadPart()**: Returns the base64-encoded payload part. - **SignaturePart()**: Returns the base64-encoded signature part. - **Header()**: Decodes and returns the token header. - **Claims()**: Decodes and returns the token claims. - **DecodeClaims(v any)**: Decodes the token claims into a provided value `v`. - **Signature()**: Returns the raw signature part of the token. ``` -------------------------------- ### Get Raw Claims Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/token.md Returns the raw claims as a JSON byte slice. Use this method to access the claims data in its original JSON format before unmarshaling. ```Go claims := token.Claims() fmt.Println(claims) // {"jti":"random-unique-string","aud":"admin"} ``` -------------------------------- ### Configure RSA-PSS Signer and Verifier Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/configuration.md Use for RSA-PSS algorithms like PS256, PS384, PS512. Requires a 2048-bit RSA private key and public key, with PSS padding and automatic salt length. ```go import ( "crypto/rand" "crypto/rsa" ) // Generate 2048-bit RSA key pair privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) publicKey := &privateKey.PublicKey // Create signer and verifier with PSS signer, _ := jwt.NewSignerPS(jwt.PS256, privateKey) verifier, _ := jwt.NewVerifierPS(jwt.PS256, publicKey) ``` -------------------------------- ### Create New HMAC Signer (Go) Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/hmac-signer.md Creates a new HMAC-based signer with the specified algorithm and secret key. Ensure the key is not empty or nil, and the algorithm is supported. ```go key := []byte("my-secret-key") signer, err := jwt.NewSignerHS(jwt.HS256, key) if err != nil { log.Fatal(err) } builder := jwt.NewBuilder(signer) claims := &jwt.RegisteredClaims{ Audience: []string{"api"}, } token, err := builder.Build(claims) if err != nil { log.Fatal(err) } fmt.Println(token.String()) ``` -------------------------------- ### Get ECDSA Algorithm Type Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/ecdsa-signer.md Retrieves the specific ECDSA algorithm (ES256, ES384, or ES512) used by an ESAlg instance. This is useful for confirming the algorithm configuration. ```Go privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) signer, _ := jwt.NewSignerES(jwt.ES256, privateKey) fmt.Println(signer.Algorithm()) // ES256 ``` -------------------------------- ### Get Signature Size for HSAlg Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/hmac-signer.md Returns the expected byte size of the signature for the configured HMAC algorithm. This is useful for pre-allocating buffers or validating signature lengths. ```go signer, _ := jwt.NewSignerHS(jwt.HS256, []byte("secret")) fmt.Println(signer.SignSize()) // 32 ``` -------------------------------- ### Supported JWT Algorithms Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/signer-verifier.md Lists the predefined constants for various JWT signing algorithms supported by the library, including HMAC, RSA, ECDSA, RSA-PSS, and EdDSA. ```go // HMAC algorithms const HS256 Algorithm = "HS256" const HS384 Algorithm = "HS384" const HS512 Algorithm = "HS512" // RSA algorithms const RS256 Algorithm = "RS256" const RS384 Algorithm = "RS384" const RS512 Algorithm = "RS512" // ECDSA algorithms const ES256 Algorithm = "ES256" const ES384 Algorithm = "ES384" const ES512 Algorithm = "ES512" // RSA-PSS algorithms const PS256 Algorithm = "PS256" const PS384 Algorithm = "PS384" const PS512 Algorithm = "PS512" // EdDSA algorithm const EdDSA Algorithm = "EdDSA" ``` -------------------------------- ### Create RSA-PSS Verifier Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/rsa-pss-signer.md This function creates a new RSA-PSS verifier. It requires a valid RSA-PSS algorithm and an RSA public key. The function returns a PSAlg verifier or an error if the provided key is nil or the algorithm is not supported. ```go func NewVerifierPS(alg Algorithm, key *rsa.PublicKey) (*PSAlg, error) ``` ```go publicKey := &privateKey.PublicKey verifier, err := jwt.NewVerifierPS(jwt.PS256, publicKey) if err != nil { log.Fatal(err) } tokenBytes := []byte("eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9...") token, err := jwt.Parse(tokenBytes, verifier) if err != nil { log.Fatal(err) } fmt.Println("Token verified successfully") ``` -------------------------------- ### Get Algorithm Type for HSAlg Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/hmac-signer.md Returns the specific HMAC algorithm (HS256, HS384, or HS512) used by an HSAlg instance. Useful for confirming the algorithm configuration. ```go signer, _ := jwt.NewSignerHS(jwt.HS256, []byte("secret")) fmt.Println(signer.Algorithm()) // HS256 ``` -------------------------------- ### Validate Token Not Before Time with IsValidNotBefore Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/claims.md Use IsValidNotBefore to determine if a token's usage window has started. This method returns true if the NotBefore claim is not set or is in the past. ```Go var claims jwt.RegisteredClaims token.DecodeClaims(&claims) if claims.IsValidNotBefore(time.Now()) { fmt.Println("Token usage window has started") } else { fmt.Println("Token cannot be used yet") } ``` -------------------------------- ### Handle JWT Errors with Direct Comparison Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/errors.md Shows how to directly compare an error against a known JWT error, such as ErrNilKey, for specific error handling. ```go signer, err := jwt.NewSignerHS(jwt.HS256, []byte("secret")) if err == jwt.ErrNilKey { // Handle nil key error } ``` -------------------------------- ### Signer.Algorithm() Method Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/signer-verifier.md Returns the algorithm identifier used by the signer. This is crucial for matching signers with appropriate verifiers. ```go func (s Signer) Algorithm() Algorithm ``` -------------------------------- ### Builder Methods Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/MANIFEST.txt Reference for the Builder constructor and its methods used to create JWT tokens, including options for setting key ID and content type. ```APIDOC ## Builder Methods ### Description Methods for constructing JWT tokens programmatically. The `NewBuilder` function initializes a new token builder, and subsequent methods allow for customization before building the final token. ### Constructor - **NewBuilder()**: Creates and returns a new `Builder` instance. ### Methods - **Build()**: Finalizes the token construction and returns the JWT string. - **WithKeyID(kid string)**: Sets the Key ID (kid) in the token header. - **WithContentType(ct string)**: Sets the Content-Type (ct) in the token header. ``` -------------------------------- ### Get ECDSA Signature Size Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/ecdsa-signer.md Returns the expected byte size of an ECDSA signature generated by the ESAlg instance. This is helpful for pre-allocating buffers or validating signature lengths. ```Go privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) signer, _ := jwt.NewSignerES(jwt.ES256, privateKey) fmt.Println(signer.SignSize()) // 64 ``` -------------------------------- ### Get Signature Size from RSAlg Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/rsa-signer.md Determines the expected byte size of the signature generated by the RSAlg. This size corresponds directly to the RSA key size used during initialization. ```go privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) signer, _ := jwt.NewSignerRS(jwt.RS256, privateKey) fmt.Println(signer.SignSize()) // 256 ``` -------------------------------- ### Create RSA-PSS Signer Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/rsa-pss-signer.md Use this function to create a new RSA-PSS signer. Ensure you provide a valid algorithm (PS256, PS384, or PS512) and an RSA private key. It returns a PSAlg signer or an error if the key is nil or the algorithm is unsupported. ```go func NewSignerPS(alg Algorithm, key *rsa.PrivateKey) (*PSAlg, error) ``` ```go // Generate a 2048-bit RSA key privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { log.Fatal(err) } signer, err := jwt.NewSignerPS(jwt.PS256, privateKey) if err != nil { log.Fatal(err) } builder := jwt.NewBuilder(signer) claims := &jwt.RegisteredClaims{ Subject: "user-789", } token, err := builder.Build(claims) if err != nil { log.Fatal(err) } fmt.Println(token.String()) ``` -------------------------------- ### Configure EdDSA Signer and Verifier Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/configuration.md Use for EdDSA algorithm. Requires a 64-byte Ed25519 private key for signing and a 32-byte public key for verification. ```go import ( "crypto/ed25519" "crypto/rand" ) // Generate Ed25519 key pair publicKey, privateKey, _ := ed25519.GenerateKey(rand.Reader) // Create signer and verifier signer, _ := jwt.NewSignerEdDSA(privateKey) verifier, _ := jwt.NewVerifierEdDSA(publicKey) ``` -------------------------------- ### Get Algorithm from RSAlg Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/rsa-signer.md Retrieves the specific RSA algorithm (RS256, RS384, or RS512) configured for the RSAlg instance. Use this to confirm the algorithm type before performing operations. ```go privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) signer, _ := jwt.NewSignerRS(jwt.RS256, privateKey) fmt.Println(signer.Algorithm()) // RS256 ``` -------------------------------- ### RSAlg Implementation Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/types.md RSA-based signer/verifier with PKCS#1 v1.5 padding. Implements both Signer and Verifier interfaces and is thread-safe for concurrent use. ```go type RSAlg struct { // unexported fields } ``` -------------------------------- ### Signer Interface Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/signer-verifier.md The Signer interface defines the methods required for any JWT signing algorithm implementation. It includes methods to get the algorithm, the signature size, and to sign a payload. ```APIDOC ## Signer Interface The `Signer` interface defines methods that any signing algorithm implementation must provide. ### Signer.Algorithm() Returns the algorithm identifier used by this signer. **Return type:** `Algorithm` - The algorithm identifier (e.g., `HS256`, `RS256`, `ES256`, `PS256`, `EdDSA`). ### Signer.SignSize() Returns the expected size in bytes of the signature produced by this signer. **Return type:** `int` - The signature size in bytes. ### Signer.Sign(payload []byte) Signs the given payload and returns the signature. #### Parameters - **payload** ([]byte) - Required - The data to sign (typically header and claims combined) **Return type:** `([]byte, error)` - The signature bytes on success, or an error if signing fails. ``` -------------------------------- ### Verifier.Algorithm() Method Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/signer-verifier.md Returns the algorithm identifier used by the verifier. This ensures that the verifier is compatible with the token's algorithm. ```go func (v Verifier) Algorithm() Algorithm ``` -------------------------------- ### Token.Header() Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/token.md Returns the decoded header structure containing algorithm, type, content type, and key ID. ```APIDOC ## Token.Header() ### Description Returns the decoded header structure containing algorithm, type, content type, and key ID. ### Method func (t *Token) Header() Header ### Return Type `Header` - The parsed token header. ### Example ```go header := token.Header() fmt.Println(header.Algorithm) // HS256 fmt.Println(header.Type) // JWT fmt.Println(header.KeyID) // "" (empty if not set) ``` ``` -------------------------------- ### NewBuilder Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/builder.md Creates a new Builder instance for constructing tokens with the specified signer and optional configuration. This builder is safe for concurrent use. ```APIDOC ## NewBuilder ### Description Creates a new Builder instance for constructing tokens with the specified signer and optional configuration. It is safe for concurrent use by multiple goroutines. ### Method `NewBuilder` ### Parameters #### Arguments - **signer** (Signer) - Required - A Signer interface implementation (e.g., HSAlg, RSAlg, ESAlg, PSAlg, EdDSAAlg). - **opts** (...BuilderOption) - Optional - Variable number of builder option functions to configure the header. ### Return type `*Builder` - A new Builder instance configured with the given signer and options. ### Example ```go key := []byte("secret") signer, err := jwt.NewSignerHS(jwt.HS256, key) if err != nil { log.Fatal(err) } // Create a basic builder builder := jwt.NewBuilder(signer) // Create a builder with options builder := jwt.NewBuilder(signer, jwt.WithKeyID("2024-key-1"), jwt.WithContentType("application/jwt"), ) ``` ``` -------------------------------- ### Configure HMAC Signer and Verifier Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/configuration.md Use for HMAC-based algorithms like HS256, HS384, HS512. Requires a secret key of at least 32 bytes for HS256. ```go key := []byte("my-secret-key-with-at-least-32-bytes") signer, _ := jwt.NewSignerHS(jwt.HS256, key) verifier, _ := jwt.NewVerifierHS(jwt.HS256, key) ``` -------------------------------- ### Parser Methods Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/MANIFEST.txt Documentation for parsing JWT tokens, including methods for parsing with verification, a convenience function for parsing claims, and a function for parsing without verification. ```APIDOC ## Parser Methods ### Description Provides functionalities to parse and validate JWT tokens. These methods handle the process of decoding token strings and verifying their signatures. ### Methods - **Parse(token string, v any)**: Parses a JWT string, verifies its signature, and decodes the claims into the provided value `v`. - **ParseClaims(token string, v any)**: A convenience function that parses a JWT string and decodes only the claims into the provided value `v`, without signature verification. - **ParseNoVerify(token string, v any)**: Parses a JWT string and decodes the claims into the provided value `v` without performing any signature verification. Use with caution. ``` -------------------------------- ### ESAlg.Algorithm() Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/ecdsa-signer.md Returns the algorithm used by this ESAlg instance. The algorithm can be ES256, ES384, or ES512. ```APIDOC ## ESAlg.Algorithm() ### Description Returns the algorithm used by this ESAlg instance. ### Method `func (es *ESAlg) Algorithm() Algorithm` ### Return Type `Algorithm` - One of `ES256`, `ES384`, or `ES512`. ### Example ```go privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) signer, _ := jwt.NewSignerES(jwt.ES256, privateKey) fmt.Println(signer.Algorithm()) // ES256 ``` ``` -------------------------------- ### Create and Sign JWT with HMAC Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/README.md Generates a JWT token using HMAC-SHA256. Ensure the key used for signing is kept secret. ```go package main import ( "fmt" "log" "time" "github.com/cristalhq/jwt/v5" ) func main() { // Create a signer (HMAC in this example) key := []byte("secret-key-for-signing") signer, err := jwt.NewSignerHS(jwt.HS256, key) if err != nil { log.Fatal(err) } // Create claims claims := &jwt.RegisteredClaims{ ID: "token-id-123", Audience: jwt.Audience{"api"}, Issuer: "my-app", Subject: "user-456", ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)), IssuedAt: jwt.NewNumericDate(time.Now()), } // Build the token builder := jwt.NewBuilder(signer) token, err := builder.Build(claims) if err != nil { log.Fatal(err) } // Get the token string fmt.Println(token.String()) // Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... } ``` -------------------------------- ### RSA Signer/Verifier Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/MANIFEST.txt Information on using RSA-based signers and verifiers, including constructors and methods for RSA algorithms (PKCS#1 v1.5). ```APIDOC ## RSA Signer/Verifier ### Description Implements the `Signer` and `Verifier` interfaces using RSA (Rivest–Shamir–Adleman) asymmetric cryptography, specifically PKCS#1 v1.5 padding. ### Constructors - **NewSignerRS(privateKey *rsa.PrivateKey)**: Creates a new RSA `Signer` using the provided private key. - **NewVerifierRS(publicKey *rsa.PublicKey)**: Creates a new RSA `Verifier` using the provided public key. ### Type - **RSAlg**: Represents an RSA algorithm (e.g., RS256, RS384, RS512). ### Methods (Implementations of Signer/Verifier interfaces) - **Algorithm()**: Returns the specific RSA algorithm. - **SignSize()**: Returns the size of the RSA signature. - **Sign(signingInput []byte)**: Generates an RSA signature for the input. - **Verify(signingInput, signature []byte)**: Verifies an RSA signature. ``` -------------------------------- ### Signer.Sign() Method Source: https://github.com/cristalhq/jwt/blob/main/_autodocs/api-reference/signer-verifier.md Signs the given payload and returns the resulting signature. The payload typically includes the JWT header and claims. ```go func (s Signer) Sign(payload []byte) ([]byte, error) ```