{"id":39250623,"url":"https://github.com/stfsy/go-jwt-cookie","last_synced_at":"2026-01-18T00:02:51.790Z","repository":{"id":320866799,"uuid":"1083600343","full_name":"stfsy/go-jwt-cookie","owner":"stfsy","description":"An opinionated Go package for creating JWT tokens and setting them as HTTP cookies with configurable security options.","archived":false,"fork":false,"pushed_at":"2025-11-24T10:09:19.000Z","size":139,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-11-27T22:49:58.565Z","etag":null,"topics":["go","golang","jwt","session-management"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/stfsy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-26T11:07:24.000Z","updated_at":"2025-11-24T10:09:15.000Z","dependencies_parsed_at":"2025-10-26T13:11:18.285Z","dependency_job_id":"78eba399-8a0d-4b16-b8a3-0ff569e7779a","html_url":"https://github.com/stfsy/go-jwt-cookie","commit_stats":null,"previous_names":["stfsy/go-jwt-cookie"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/stfsy/go-jwt-cookie","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stfsy%2Fgo-jwt-cookie","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stfsy%2Fgo-jwt-cookie/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stfsy%2Fgo-jwt-cookie/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stfsy%2Fgo-jwt-cookie/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/stfsy","download_url":"https://codeload.github.com/stfsy/go-jwt-cookie/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stfsy%2Fgo-jwt-cookie/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28523047,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-17T23:53:28.710Z","status":"ssl_error","status_checked_at":"2026-01-17T23:52:20.131Z","response_time":85,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["go","golang","jwt","session-management"],"created_at":"2026-01-18T00:02:51.337Z","updated_at":"2026-01-18T00:02:51.668Z","avatar_url":"https://github.com/stfsy.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# go-jwt-cookie\n\nAn opinionated Go package for creating JWT tokens and setting them as HTTP cookies with configurable security options.\n\nThis library is intended to support your existing **session management**. It offers:\n\n- JWT token signing with standard and custom claims\n- JWT token validation and claims extraction\n- Configurable cookie options (Secure, HttpOnly, SameSite, etc.)\n- Signing key rotation support for seamless key updates\n- Simple constructor-based configuration pattern\n\nThe library itself does not provide any **session management** mechanism for managing session metadata, invalidation, or expiration.\n\n## Why use it\nIn most web applications you need to manage user sessions. Storing a session ID in a signed JWT in an HTTP-only, Secure cookie allows you to verify the integrity of the JWT directly on the server (without a database lookup). Thus, you can safely reject tampered tokens without needing to query a backend store.\n\nThis approach doesn’t prevent you from storing session metadata in a database. In fact, combining both is recommended: keep a server-side session record so you can invalidate sessions, track activity, and implement logout and forced expiration. Note that JWTs are signed, not encrypted—don’t place secrets in claims.\n\n## Installation\n\nUse the module path shown in `go.mod`:\n\n```bash\ngo get github.com/stfsy/go-jwt-cookie\n```\n\n## Quick Usage\n\nThe simplest integration is to create a cookie manager and use it to set JWT cookies:\n\n```go\npackage main\n\nimport (\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/stfsy/go-jwt-cookie\"\n)\n\nfunc main() {\n    // Create a cookie manager with secure options\n     manager := jwtcookie.NewCookieManager(\n\t \tjwtcookie.WithSecure(true),\n\t \tjwtcookie.WithHTTPOnly(true),\n      \t// kidSalt (second argument) is required and influences deterministic KID derivation for HMAC keys.\n      \t// Use a secret, random, non-empty salt consistent across instances. Minimum 16 bytes recommended (32 bytes preferred).\n      \tjwtcookie.WithSigningKeyHMAC(\n      \t\t[]byte(\"production-signing-key-that-is-at-least-32-bytes-long\"),\n      \t\t[]byte(\"0123456789abcdef\"), // 16-byte salt example; prefer 32 random bytes in production\n      \t),\n\t \tjwtcookie.WithSigningMethod(jwt.SigningMethodHS256),\n\t \tjwtcookie.WithIssuer(\"https://my-signing-service-url.domain\"),\n\t \tjwtcookie.WithAudience(\"https://my-validating-service-url.domain\"),\n\t )\n\n\thttp.HandleFunc(\"/login\", func(w http.ResponseWriter, r *http.Request) {\n\t\t// Create custom claims\n\t\tclaims := map[string]string{\n\t\t\t\"user_id\": \"12345\",\n\t\t\t\"role\":    \"admin\",\n\t\t}\n\n\t\t// Set JWT cookie\n\t\terr := manager.SetJWTCookie(w, r, claims)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"JWT cookie set successfully\"))\n\t})\n\n\thttp.HandleFunc(\"/protected\", func(w http.ResponseWriter, r *http.Request) {\n\t\t// Validate JWT and get claims\n\t\tclaims, err := manager.GetClaimsOfValid(r)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Unauthorized\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\tuserID := claims[\"user_id\"]\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"Welcome, user: \" + userID.(string)))\n\t})\n\n\thttp.ListenAndServe(\":8080\", nil)\n}\n```\n\n## Key Rotation\n\nThe library supports signing key rotation, allowing you to validate tokens signed with old keys while signing new tokens with a new key:\n\n```go\noldKey := []byte(\"old-signing-key\")\nnewKey := []byte(\"new-signing-key\")\n\nmanager := jwtcookie.NewCookieManager(\n\t// Use a secret salt of at least 16 bytes (32 preferred) and keep it consistent across instances\n\tjwtcookie.WithSigningKeyHMAC(newKey, []byte(\"0123456789abcdef\")),  // 16-byte salt example; prefer 32 random bytes in production\n\tjwtcookie.WithValidationKeysHMAC([][]byte{newKey, oldKey}),  // Accept both keys for validation\n \tjwtcookie.WithSigningMethod(jwt.SigningMethodHS256),\n \tjwtcookie.WithIssuer(\"your-service-name\"),\n \tjwtcookie.WithAudience(\"your-frontend-app\"),\n)\n\n// New tokens will be signed with newKey\n// Old tokens signed with oldKey will still validate successfully\n```\n\n## RSA and ECDSA Examples\n\n### Using RSA Keys\n\n```go\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\n\t\"github.com/golang-jwt/jwt/v5\"\n\t\"github.com/stfsy/go-jwt-cookie\"\n)\n\n// Generate RSA key pair\nprivateKey, _ := rsa.GenerateKey(rand.Reader, 2048)\n\nmanager := jwtcookie.NewCookieManager(\n\tjwtcookie.WithSigningKeyRSA(privateKey),\n\tjwtcookie.WithSigningMethod(jwt.SigningMethodRS256),\n\tjwtcookie.WithIssuer(\"your-service-name\"),\n\tjwtcookie.WithAudience(\"your-frontend-app\"),\n)\n\n// For validation with public keys only\nmanager := jwtcookie.NewCookieManager(\n\tjwtcookie.WithSigningKeyRSA(privateKey),\n\tjwtcookie.WithSigningMethod(jwt.SigningMethodRS256),\n\tjwtcookie.WithValidationKeysRSA([]*rsa.PublicKey{\u0026privateKey.PublicKey}),\n\tjwtcookie.WithIssuer(\"your-service-name\"),\n\tjwtcookie.WithAudience(\"your-frontend-app\"),\n)\n\n// Example: RSA-PSS (RSAPSS) using PS256\n// Use the RSA private key for signing with RSAPSS (PS256)\nmanagerPS, _ := jwtcookie.NewCookieManager(\n\tjwtcookie.WithSigningKeyRSA(privateKey),\n\tjwtcookie.WithSigningMethodPS256(),\n\tjwtcookie.WithValidationKeysRSA([]*rsa.PublicKey{\u0026privateKey.PublicKey}),\n\tjwtcookie.WithIssuer(\"your-service-name\"),\n\tjwtcookie.WithAudience(\"your-frontend-app\"),\n)\n```\n\n### Using ECDSA Keys\n\n```go\nimport (\n\t\"crypto/ecdsa\"\n\t\"crypto/elliptic\"\n\t\"crypto/rand\"\n\t\n\t\"github.com/golang-jwt/jwt/v5\"\n\t\"github.com/stfsy/go-jwt-cookie\"\n)\n\n// Generate ECDSA key pair\nprivateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\nmanager := jwtcookie.NewCookieManager(\n\tjwtcookie.WithSigningKeyECDSA(privateKey),\n\tjwtcookie.WithSigningMethod(jwt.SigningMethodES256),\n\tjwtcookie.WithIssuer(\"your-service-name\"),\n\tjwtcookie.WithAudience(\"your-frontend-app\"),\n)\n```\n```\n\n## Configuration Options\n\nThe cookie manager supports the following configuration options:\n\n- `WithSecure(bool)` — sets the Secure flag on the cookie (HTTPS only)\n- `WithHTTPOnly(bool)` — sets the HttpOnly flag to prevent JavaScript access\n- `WithMaxAge(int)` — sets cookie expiration in seconds\n- `WithSameSite(http.SameSite)` — sets the SameSite attribute\n- `WithDomain(string)` — sets the cookie domain\n- `WithPath(string)` — sets the cookie path\n- `WithCookieName(string)` — sets a custom cookie name\n- `WithSigningKeyHMAC([]byte, []byte)`, `WithSigningKeyRSA(*rsa.PrivateKey)`, `WithSigningKeyECDSA(*ecdsa.PrivateKey)` — typed helpers to set the signing key for signing JWTs\n\t- For HMAC (HS256, HS384, HS512): use `WithSigningKeyHMAC(key, kidSalt)` where `kidSalt` is required (non-empty). The KID is derived as `base64url(HMAC-SHA256(kidSalt, key)[:16])`. Use a secret, random salt consistent across instances.\n\t- For RSA (RS256, RS384, RS512, PS256, PS384, PS512): use `WithSigningKeyRSA(*rsa.PrivateKey)`\n\t- For ECDSA (ES256, ES384, ES512): use `WithSigningKeyECDSA(*ecdsa.PrivateKey)`\n- `WithIssuer(string)`, `WithAudience(string)`  — required; used for iss/aud/sub claims and enforced during validation\n- `WithValidationKeysHMAC([][]byte)`, `WithValidationKeysRSA([]*rsa.PublicKey)`, `WithValidationKeysECDSA([]*ecdsa.PublicKey)` — typed helpers to set multiple keys for validation (supports key rotation)\n\t- For HMAC: pass `WithValidationKeysHMAC([][]byte)`\n\t- For RSA: pass `WithValidationKeysRSA([]*rsa.PublicKey)`\n\t- For ECDSA: pass `WithValidationKeysECDSA([]*ecdsa.PublicKey)`\n- `WithSigningMethod(jwt.SigningMethod)` — sets the JWT signing algorithm\n  - HMAC: HS256 (default), HS384, HS512\n  - RSA: RS256, RS384, RS512, PS256, PS384, PS512\n  - ECDSA: ES256, ES384, ES512\n- `WithLeeway(time.Duration)` — optionally applies a clock-skew leeway during validation for `exp`/`nbf`/`iat` claims. If unset or \u003c= 0, no leeway is applied. Example: `WithLeeway(30*time.Second)`.\n- `WithTimeFunc(func() time.Time)` — optionally injects a custom time source for validation (useful for tests or controlled environments). When not provided, the default time source is used.\n\n## Testing\n\nUnit tests are provided and can be run with:\n\n```bash\ngo test ./...\n```\n\nOr use the included test script:\n\n```bash\n./test.sh\n```\n\n## Fuzzing\n\nFuzz tests are provided to ensure robustness. Run them with:\n\n```bash\n./fuzz.sh\n```\n\n## Security Considerations\n\n- Always use `WithSecure(true)` in production to ensure cookies are only sent over HTTPS\n- Use `WithHTTPOnly(true)` to prevent XSS attacks from accessing the token\n- Consider using `WithSameSite(http.SameSiteStrictMode)` to prevent CSRF attacks\n- Use a strong signing key for signing JWT tokens\n- Use `WithSigningMethod()` to select an appropriate algorithm (HS256, HS384, HS512; or RS*/PS*/ES*)\n- Provide `WithIssuer`, `WithAudience` and keep them consistent across services; tokens lacking these claims will be rejected.\n- For HMAC, ensure keys meet minimum sizes (HS256: 32 bytes, HS384: 48 bytes, HS512: 64 bytes)\n- Account for clock skew between services. Consider configuring a small leeway (e.g., 30s) via `WithLeeway(30*time.Second)`.\n\n### Cookie name prefixes\n\nThis library enforces standard cookie prefix semantics when the cookie name uses these prefixes: \n- `__Host-\u003cname\u003e`: cookie is always set with `Secure=true`, `Path=/`, and without a `Domain` attribute. Conflicting options are overridden at construction time.\n- `__Secure-\u003cname\u003e`: cookie is always set with `Secure=true`. `Domain` and `Path` remain as configured.\n- `__Host-Http-\u003cname\u003e`: same as `__Host-` and also forces `HttpOnly=true`.\n- `__Http-\u003cname\u003e`: forces `HttpOnly=true` and `Secure=true`.\n\nExample (`__Host-`):\n\n```go\nmanager, err := jwtcookie.NewCookieManager(\n\tjwtcookie.WithCookieName(\"__Host-session\"),\n\tjwtcookie.WithSecure(false),         // will be set to true\n\tjwtcookie.WithDomain(\"example.com\"), // domain won't be set even though provided\n\tjwtcookie.WithPath(\"/sub\"),          // will be set to \"/\"\n\t// ... signing method/keys, iss/aud, validation keys\n)\n```\n\nExample (`__Secure-`):\nExample (`__Host-Http-`):\n\n```go\nmanager, err := jwtcookie.NewCookieManager(\n\tjwtcookie.WithCookieName(\"__Host-Http-session\"),\n\t// HttpOnly forced true; Secure true, Path=/, Domain cleared\n)\n```\n\nExample (`__Http-`):\n\n```go\nmanager, err := jwtcookie.NewCookieManager(\n\tjwtcookie.WithCookieName(\"__Http-session\"),\n\t// HttpOnly and Secure forced true; Domain/Path unchanged\n)\n```\n\n```go\nmanager, err := jwtcookie.NewCookieManager(\n\tjwtcookie.WithCookieName(\"__Secure-session\"),\n\tjwtcookie.WithSecure(false),         // will be set to true\n\tjwtcookie.WithDomain(\"example.com\"), // domain won't be set even though provided\n\tjwtcookie.WithPath(\"/sub\"),          // will be set to \"/\"\n\t// ... signing method/keys, iss/aud, validation keys\n)\n```\n\nSee [MDN Web Docs on Cookie Prefixes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes) for more details.\n\n## Contributing\n\n1. Fork the repository and create a branch.\n2. Run tests and linters locally using `test.sh` and `lint.sh`.\n3. Make a small, focused change with corresponding tests.\n4. Open a PR with a clear description.\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstfsy%2Fgo-jwt-cookie","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstfsy%2Fgo-jwt-cookie","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstfsy%2Fgo-jwt-cookie/lists"}