{"id":45163941,"url":"https://github.com/go-authgate/authgate","last_synced_at":"2026-03-08T15:03:24.840Z","repository":{"id":331560267,"uuid":"1128824463","full_name":"go-authgate/authgate","owner":"go-authgate","description":"A lightweight OAuth 2.0 Authorization Server supporting Device Authorization Grant (RFC 8628) and Authorization Code Flow with PKCE (RFC 6749 + RFC 7636), developed using Go and the Gin framework.","archived":false,"fork":false,"pushed_at":"2026-02-25T14:41:35.000Z","size":6591,"stargazers_count":25,"open_issues_count":2,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-02-25T18:27:03.589Z","etag":null,"topics":["authorization","authorization-code-grant","device","oauth2","oauth2-server"],"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/go-authgate.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"docs/SECURITY.md","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},"funding":{"github":null,"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"lfx_crowdfunding":null,"custom":["https://www.paypal.me/appleboy46"]}},"created_at":"2026-01-06T07:49:29.000Z","updated_at":"2026-02-25T14:24:59.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/go-authgate/authgate","commit_stats":null,"previous_names":["appleboy/authgate","go-authgate/authgate"],"tags_count":13,"template":false,"template_full_name":null,"purl":"pkg:github/go-authgate/authgate","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-authgate%2Fauthgate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-authgate%2Fauthgate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-authgate%2Fauthgate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-authgate%2Fauthgate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/go-authgate","download_url":"https://codeload.github.com/go-authgate/authgate/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-authgate%2Fauthgate/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29939040,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-28T13:49:17.081Z","status":"ssl_error","status_checked_at":"2026-02-28T13:48:50.396Z","response_time":90,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: 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":["authorization","authorization-code-grant","device","oauth2","oauth2-server"],"created_at":"2026-02-20T06:19:42.097Z","updated_at":"2026-03-06T08:11:32.954Z","avatar_url":"https://github.com/go-authgate.png","language":"Go","readme":"# AuthGate\n\n\u003e A lightweight OAuth 2.0 Authorization Server supporting Device Authorization Grant ([RFC 8628][rfc8628]), Authorization Code Flow with PKCE ([RFC 6749][rfc6749] + [RFC 7636][rfc7636]), and Client Credentials Grant for machine-to-machine authentication\n\n[![Security Scanning](https://github.com/go-authgate/authgate/actions/workflows/security.yml/badge.svg)](https://github.com/go-authgate/authgate/actions/workflows/security.yml)\n[![Lint and Testing](https://github.com/go-authgate/authgate/actions/workflows/testing.yml/badge.svg)](https://github.com/go-authgate/authgate/actions/workflows/testing.yml)\n[![Go Report Card](https://goreportcard.com/badge/github.com/go-authgate/authgate)](https://goreportcard.com/report/github.com/go-authgate/authgate)\n[![codecov](https://codecov.io/gh/go-authgate/authgate/graph/badge.svg?token=z0Eq9k5Vwi)](https://codecov.io/gh/go-authgate/authgate)\n[![Go Reference](https://pkg.go.dev/badge/github.com/go-authgate/authgate.svg)](https://pkg.go.dev/github.com/go-authgate/authgate)\n[![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)\n\n## Table of Contents\n\n- [AuthGate](#authgate)\n  - [Table of Contents](#table-of-contents)\n  - [Why AuthGate?](#why-authgate)\n    - [The Enterprise Case for AuthGate](#the-enterprise-case-for-authgate)\n      - [1. Fragmented authentication — every service re-inventing LDAP integration](#1-fragmented-authentication--every-service-re-inventing-ldap-integration)\n      - [2. No token lifecycle management — tokens issued, never tracked or revoked](#2-no-token-lifecycle-management--tokens-issued-never-tracked-or-revoked)\n      - [3. Service owners have no visibility or control over who is using their service](#3-service-owners-have-no-visibility-or-control-over-who-is-using-their-service)\n  - [✨ Key Features](#-key-features)\n  - [🚀 Quick Start](#-quick-start)\n    - [Prerequisites](#prerequisites)\n    - [Installation](#installation)\n    - [Run the Server](#run-the-server)\n    - [Test with Example CLI](#test-with-example-cli)\n  - [📖 Documentation](#-documentation)\n    - [Getting Started](#getting-started)\n    - [Development](#development)\n    - [Operations](#operations)\n    - [Advanced Topics](#advanced-topics)\n  - [🎯 How It Works](#-how-it-works)\n    - [Device Code Flow (RFC 8628) — for CLI / IoT](#device-code-flow-rfc-8628--for-cli--iot)\n    - [Authorization Code Flow (RFC 6749) — for Web / Mobile](#authorization-code-flow-rfc-6749--for-web--mobile)\n    - [Client Credentials Grant (RFC 6749 §4.4) — for Machine-to-Machine](#client-credentials-grant-rfc-6749-44--for-machine-to-machine)\n  - [🎨 User Interface](#-user-interface)\n    - [Login \\\u0026 Authorization Flow](#login--authorization-flow)\n    - [Session Management](#session-management)\n  - [⚙️ Configuration](#️-configuration)\n    - [Basic Configuration (.env)](#basic-configuration-env)\n    - [Advanced Features](#advanced-features)\n  - [🏗️ Architecture](#️-architecture)\n    - [Technology Stack](#technology-stack)\n    - [Project Structure](#project-structure)\n  - [🚀 Deployment](#-deployment)\n    - [Docker Deployment](#docker-deployment)\n    - [Production Deployment](#production-deployment)\n  - [🔒 Security](#-security)\n    - [Production Checklist](#production-checklist)\n    - [What AuthGate Protects](#what-authgate-protects)\n  - [📊 Performance](#-performance)\n    - [Benchmarks (Reference)](#benchmarks-reference)\n    - [Scalability](#scalability)\n  - [🔧 Development](#-development)\n    - [Build from Source](#build-from-source)\n    - [Extending AuthGate](#extending-authgate)\n  - [❓ FAQ](#-faq)\n    - [Q: Why not use OAuth password grant?](#q-why-not-use-oauth-password-grant)\n    - [Q: Can I use this in production?](#q-can-i-use-this-in-production)\n    - [Q: How do I add user registration?](#q-how-do-i-add-user-registration)\n    - [Q: Does it support refresh tokens?](#q-does-it-support-refresh-tokens)\n    - [Q: How do users revoke device access?](#q-how-do-users-revoke-device-access)\n    - [Q: Does it support Authorization Code Flow for web apps?](#q-does-it-support-authorization-code-flow-for-web-apps)\n    - [Q: Does it support machine-to-machine (M2M) authentication?](#q-does-it-support-machine-to-machine-m2m-authentication)\n  - [🤝 Contributing](#-contributing)\n  - [📄 License](#-license)\n  - [📚 References](#-references)\n  - [🙏 Acknowledgments](#-acknowledgments)\n\n---\n\n## Why AuthGate?\n\nModern CLI tools and IoT devices need secure user authentication, but traditional OAuth flows don't work well for devices without browsers or keyboards. **AuthGate** implements the OAuth 2.0 Device Authorization Grant ([RFC 8628][rfc8628]), allowing users to authenticate on a separate device while keeping credentials secure.\n\nAuthGate also serves as a lightweight **centralised identity gateway** for internal platforms — unifying login across enterprise tools, giving every user full visibility and control over their active sessions and per-app grants, and providing security teams with a complete audit trail of all authentication events.\n\n**Perfect for:**\n\n- 🖥️ CLI tools (like `gh`, `aws-cli`) — **Device Code Flow**\n- 📺 Smart TVs, IoT devices, gaming consoles — **Device Code Flow**\n- 🌐 Web applications with server-side backends — **Authorization Code Flow (confidential)**\n- 📱 Single-page apps and mobile apps — **Authorization Code Flow + PKCE (public)**\n- 🤖 CI/CD pipelines and automation scripts — **Device Code Flow** or **Client Credentials**\n- ⚙️ Microservices and server-to-server APIs — **Client Credentials Grant**\n- 🏢 Enterprise teams needing **token self-service** — users manage and revoke their own active sessions and per-app grants via the built-in web UI (`/account/sessions`, `/account/authorizations`), no admin intervention required\n- 🔑 Organisations wanting a **unified internal SSO portal** — centralise login across all internal tools and services through a single OAuth 2.0 gateway, eliminating per-system password management\n- 🔍 **Security \u0026 compliance teams** — comprehensive audit logs of every authentication, token, and admin event with filtering and CSV export (`/admin/audit`), satisfying audit and regulatory requirements\n\n### The Enterprise Case for AuthGate\n\n#### 1. Fragmented authentication — every service re-inventing LDAP integration\n\n**The problem:** Internal platforms (MCPs, skill services, bots, web tools, CLIs) each implement their own authentication logic. Most connect directly to LDAP, but with inconsistent patterns, password-handling rules, and session/token quality — resulting in security risk, duplicated effort, and high maintenance cost:\n\n- Every team reinvents password validation, hashing, and policy enforcement.\n- LDAP credentials and bind passwords are scattered across codebases.\n- Any LDAP schema change or credential rotation forces simultaneous updates and redeployments across all services.\n- There is no single, consistent login record across the organisation for audit purposes.\n\n**How AuthGate helps:** A single **Identity Gateway** that all services integrate with as a standard OAuth 2.0 / OIDC client — no more direct LDAP wiring:\n\n- Outward-facing: standard OAuth 2.0 APIs (Device Code, PKCE, Client Credentials).\n- Inward-facing: centralised handling of LDAP, GitHub, Microsoft, and other identity sources.\n- New services register as OAuth clients and never touch LDAP directly.\n\n#### 2. No token lifecycle management — tokens issued, never tracked or revoked\n\n**The problem:** Basic OAuth implementations (like many internal MCPs) lack centralised token storage, leaving organisations unable to answer: _Who has a valid token? When does it expire? Can it be revoked?_\n\n- No central record of issued tokens or active sessions.\n- No refresh token rotation, expiry policy, or revocation capability.\n- No audit trail: who logged in, when, from where, and which token was used?\n- During a security incident, there is no fast path to revoke a token, trace its origin, or force a platform-wide re-login.\n\n**How AuthGate helps:** Full token lifecycle management out of the box:\n\n- Users self-serve at `/account/sessions` and `/account/authorizations` to inspect and revoke active sessions and per-app grants.\n- Admins can force all users of any client to re-authenticate with a single action.\n- Complete **Audit Trails** at `/admin/audit` with CSV export satisfy incident investigation and compliance requirements.\n\n#### 3. Service owners have no visibility or control over who is using their service\n\n**The problem:** Without a centralised authorisation layer, service owners cannot answer basic operational questions:\n\n- Which users currently have access to this service?\n- When was their authorisation granted, and when does it expire?\n- What scopes were approved, and can they be narrowed?\n- How do I produce a login history, IP list, and token scope report for an audit?\n\n**How AuthGate helps:** A unified OAuth client management console gives every service owner full **visibility**, **control**, and **auditability**:\n\n- Configure client scopes, redirect URIs, token TTLs, and user authorisation records in one place.\n- View all token activity for a service in real time.\n- Revoke any user's authorisation instantly.\n- Respond to audits and security requests without digging through disparate system logs.\n\n---\n\n## ✨ Key Features\n\n- **Three OAuth 2.0 Grant Types**: Device Authorization Grant ([RFC 8628][rfc8628]) for CLI/IoT, Authorization Code Flow with PKCE ([RFC 6749][rfc6749] + [RFC 7636][rfc7636]) for web/mobile apps, and Client Credentials Grant ([RFC 6749][rfc6749] §4.4) for machine-to-machine authentication\n- **OIDC ID Token \u0026 UserInfo**: When `TOKEN_PROVIDER_MODE=local`, issues a signed `id_token` (OIDC Core 1.0) alongside the access token when `openid` scope is granted. In `TOKEN_PROVIDER_MODE=http_api`, no ID tokens are generated. Supports `nonce`, `at_hash`, and scope-gated profile/email claims. Includes `/.well-known/openid-configuration` discovery and `/oauth/userinfo` endpoints.\n- **User Consent Management**: Users can review and revoke per-app access at `/account/authorizations`; admins can force re-authentication for all users of any client\n- **Security First**: Rate limiting, audit logging, CSRF protection, PKCE enforcement, and session management built-in\n- **Production Ready**: Built-in monitoring with Prometheus metrics, health checks, comprehensive audit trails, and graceful shutdown with configurable timeouts\n- **Zero Dependencies**: Single static binary with SQLite embedded, or use PostgreSQL for scale\n- **Multi-Auth Support**: Local authentication, external HTTP API, OAuth providers (GitHub, Gitea, Microsoft)\n- **Flexible Deployment**: Docker-ready, cloud-friendly, runs anywhere with context-aware lifecycle management\n- **Token Management**: Fixed and rotation refresh token modes, web UI for session management\n\n---\n\n## 🚀 Quick Start\n\n### Prerequisites\n\n- Go 1.25 or higher\n- Make (optional, but recommended)\n\n### Installation\n\n```bash\n# Clone repository\ngit clone \u003crepository-url\u003e\ncd authgate\n\n# Copy environment configuration\ncp .env.example .env\n\n# Generate strong secrets\necho \"JWT_SECRET=$(openssl rand -hex 32)\" \u003e\u003e .env\necho \"SESSION_SECRET=$(openssl rand -hex 32)\" \u003e\u003e .env\n\n# Build the server\nmake build\n```\n\n### Run the Server\n\n```bash\n# Start server\n./bin/authgate server\n\n# Or with Docker\ndocker run -d \\\n  --name authgate \\\n  -p 8080:8080 \\\n  -v authgate-data:/app/data \\\n  -e JWT_SECRET=$(openssl rand -hex 32) \\\n  -e SESSION_SECRET=$(openssl rand -hex 32) \\\n  -e BASE_URL=http://localhost:8080 \\\n  authgate:latest\n```\n\nServer starts on `http://localhost:8080`\n\n**Important:** Note the `client_id` printed in startup logs - you'll need this for the CLI example.\n\n### Test with Example CLI\n\nTwo example CLIs are available. Each demonstrates a different OAuth 2.0 flow.\n\n**Device Code Flow** ([github.com/go-authgate/device-cli](https://github.com/go-authgate/device-cli)) — for headless environments:\n\n```bash\ngit clone https://github.com/go-authgate/device-cli\ncd device-cli\n\n# Configure client\ncp .env.example .env\nnano .env  # Add CLIENT_ID from server logs\n\n# Run the CLI\ngo run main.go\n```\n\n**Authorization Code Flow** ([github.com/go-authgate/oauth-cli](https://github.com/go-authgate/oauth-cli)) — for apps that can open a browser:\n\n```bash\ngit clone https://github.com/go-authgate/oauth-cli\ncd oauth-cli\n\n# Configure client\ncp .env.example .env\nnano .env  # Add CLIENT_ID (and CLIENT_SECRET for confidential clients)\n\n# Run the CLI\ngo run .\n```\n\nThe Authorization Code Flow CLI starts a local callback server, opens your browser at the consent page, and exchanges the returned code for tokens automatically. It supports both **public clients (PKCE)** and **confidential clients**.\n\n**Hybrid Flow** ([github.com/go-authgate/cli](https://github.com/go-authgate/cli)) — auto-detects the environment and picks the right flow. On a local machine the CLI opens a browser (Authorization Code Flow + PKCE). In an SSH session or headless environment it automatically falls back to Device Code Flow.\n\n---\n\n## 📖 Documentation\n\n### Getting Started\n\n- **[Quick Start](#-quick-start)** - Get up and running in 5 minutes\n- **[Configuration Guide](docs/CONFIGURATION.md)** - Environment variables, secrets, OAuth setup, rate limiting\n- **[Deployment Guide](docs/DEPLOYMENT.md)** - Production deployment with Docker, systemd, Nginx, cloud platforms\n\n### Development\n\n- **[Architecture Guide](docs/ARCHITECTURE.md)** - System design, flow diagrams, database schema\n- **[Development Guide](docs/DEVELOPMENT.md)** - Building, testing, and extending AuthGate\n\n### Operations\n\n- **[Monitoring Guide](docs/MONITORING.md)** - Health checks, metrics, audit logging, alerting\n- **[Prometheus Metrics](docs/METRICS.md)** - Metrics endpoint, authentication, Grafana dashboards\n- **[Security Guide](docs/SECURITY.md)** - Production checklist, threat model, secrets management\n- **[Troubleshooting](docs/TROUBLESHOOTING.md)** - Common issues, debug mode, FAQ\n\n### Advanced Topics\n\n- **[Authorization Code Flow Guide](docs/AUTHORIZATION_CODE_FLOW.md)** - Auth Code Flow, PKCE, user consent, admin controls\n- **[Client Credentials Flow Guide](docs/CLIENT_CREDENTIALS_FLOW.md)** - Machine-to-machine authentication, M2M token management\n- **[OAuth Setup Guide](docs/OAUTH_SETUP.md)** - GitHub, Gitea, Microsoft Entra ID integration\n- **[Rate Limiting Guide](docs/RATE_LIMITING.md)** - Protect against brute force and API abuse\n- **[Performance Guide](docs/PERFORMANCE.md)** - Scalability, optimization, benchmarks\n- **[Use Cases](docs/USE_CASES.md)** - Real-world examples and code samples\n\n---\n\n## 🎯 How It Works\n\nAuthGate supports three OAuth 2.0 grant types.\n\n### Device Code Flow ([RFC 8628][rfc8628]) — for CLI / IoT\n\n```mermaid\nsequenceDiagram\n    participant CLI as CLI Tool\n    participant AuthGate as AuthGate Server\n    participant User as User (Browser)\n\n    CLI-\u003e\u003eAuthGate: 1. Request device code\n    AuthGate--\u003e\u003eCLI: device_code + user_code + URL\n\n    Note over CLI: Display: \"Visit URL, Enter code\"\n\n    User-\u003e\u003eAuthGate: 2. Visit URL, login, enter code\n    AuthGate--\u003e\u003eUser: ✅ Success\n\n    CLI-\u003e\u003eAuthGate: 3. Poll for token\n    AuthGate--\u003e\u003eCLI: access_token + refresh_token\n```\n\n### Authorization Code Flow ([RFC 6749][rfc6749]) — for Web / Mobile\n\n```mermaid\nsequenceDiagram\n    participant App as Web/Mobile App\n    participant Browser as Browser\n    participant AuthGate as AuthGate Server\n\n    App-\u003e\u003eBrowser: 1. Redirect to /oauth/authorize\n    Browser-\u003e\u003eAuthGate: Login + Consent page\n    AuthGate-\u003e\u003eBrowser: 302 redirect_uri?code=XXXXX\n    Browser-\u003e\u003eApp: code delivered to callback\n    App-\u003e\u003eAuthGate: 2. POST /oauth/token (code + secret or PKCE)\n    AuthGate--\u003e\u003eApp: access_token + refresh_token [+ id_token if openid scope]\n```\n\n**[Authorization Code Flow Guide →](docs/AUTHORIZATION_CODE_FLOW.md)**\n\n### Client Credentials Grant ([RFC 6749][rfc6749] §4.4) — for Machine-to-Machine\n\n```mermaid\nsequenceDiagram\n    participant Svc as Service / Daemon\n    participant AuthGate as AuthGate Server\n\n    Svc-\u003e\u003e+AuthGate: POST /oauth/token\u003cbr/\u003egrant_type=client_credentials\u003cbr/\u003eclient_id + client_secret (Basic Auth)\n    AuthGate--\u003e\u003e-Svc: access_token (no refresh token)\n\n    Note over Svc: Token stored in memory\u003cbr/\u003ere-requested when expired\n```\n\n- Requires a **confidential client** with `Client Credentials Flow` enabled in admin\n- No user involved — authenticates the client application itself\n- No refresh token is issued; the client simply requests a new token when the current one expires\n- Scope can be restricted per-request (must be a subset of the client's registered scopes)\n- `openid` and `offline_access` scopes are not permitted (user-centric OIDC scopes)\n\n**[Client Credentials Flow Guide →](docs/CLIENT_CREDENTIALS_FLOW.md)**\n\n**Key Endpoints:**\n\n| Endpoint                            | Method   | Purpose                                                                                    |\n| ----------------------------------- | -------- | ------------------------------------------------------------------------------------------ |\n| `/.well-known/openid-configuration` | GET      | OIDC Discovery metadata                                                                    |\n| `/oauth/device/code`                | POST     | Request device code (CLI)                                                                  |\n| `/oauth/authorize`                  | GET      | Authorization consent page (web apps)                                                      |\n| `/oauth/authorize`                  | POST     | Submit consent decision                                                                    |\n| `/oauth/token`                      | POST     | Token endpoint: `device_code`, `authorization_code`, `refresh_token`, `client_credentials` |\n| `/oauth/tokeninfo`                  | GET      | Verify token validity                                                                      |\n| `/oauth/userinfo`                   | GET/POST | OIDC UserInfo — profile claims for token owner                                             |\n| `/oauth/revoke`                     | POST     | Revoke tokens ([RFC 7009][rfc7009])                                                        |\n| `/device`                           | GET      | Device code entry page (browser)                                                           |\n| `/account/sessions`                 | GET      | Manage active token sessions                                                               |\n| `/account/authorizations`           | GET      | Manage per-app consent grants                                                              |\n| `/admin/clients/:id/authorizations` | GET      | Admin: view all authorized users for a client                                              |\n| `/admin/clients/:id/revoke-all`     | POST     | Admin: force re-auth for all users                                                         |\n| `/health`                           | GET      | Health check                                                                               |\n| `/metrics`                          | GET      | Prometheus metrics (optional auth)                                                         |\n\n**[Full API Reference →](docs/ARCHITECTURE.md#key-endpoints)** | **[Metrics Documentation →](docs/METRICS.md)**\n\n---\n\n## 🎨 User Interface\n\nAuthGate provides a clean, modern web interface:\n\n### Login \u0026 Authorization Flow\n\n![Login Page](images/login-page.png)\n_Simple username/password authentication_\n\n![Device Authorization](images/device-page.png)\n_Enter the code from your CLI tool_\n\n![Success](images/authorization-successful.png)\n_Confirmation and return to CLI_\n\n### Session Management\n\nUsers can view and revoke active sessions at `/account/sessions`:\n\n- View all authorized devices\n- See client information and authorization times\n- Revoke specific devices or all at once\n- Monitor active vs expired sessions\n\nUsers can manage per-app consent grants at `/account/authorizations`:\n\n- See which web/mobile apps have been granted access\n- View the approved scopes per app\n- Revoke access for any individual app (revokes all associated tokens)\n\n---\n\n## ⚙️ Configuration\n\n### Basic Configuration (.env)\n\n```bash\n# Server\nSERVER_ADDR=:8080\nBASE_URL=http://localhost:8080\n\n# Security (REQUIRED - use openssl rand -hex 32)\nJWT_SECRET=your-256-bit-secret-change-in-production\nSESSION_SECRET=your-session-secret-change-in-production\n\n# Database\nDATABASE_DRIVER=sqlite          # or postgres\nDATABASE_DSN=oauth.db\n\n# Admin Password (REQUIRED in production)\nDEFAULT_ADMIN_PASSWORD=your-secure-password\n\n# Features\nENABLE_RATE_LIMIT=true          # Brute force protection\nENABLE_AUDIT_LOGGING=true       # Comprehensive audit trails\n\n# Monitoring (Optional - disabled by default)\n# METRICS_ENABLED=true            # Enable Prometheus metrics endpoint\n# METRICS_TOKEN=your-bearer-token # Bearer token for /metrics (optional)\n```\n\n**[Complete Configuration Guide →](docs/CONFIGURATION.md)**\n\n### Advanced Features\n\n- **OAuth Third-Party Login**: GitHub, Gitea, Microsoft Entra ID\n- **External Authentication**: Integrate with existing auth systems\n- **Pluggable Token Providers**: Use external token services\n- **Service-to-Service Auth**: HMAC or simple header authentication\n- **HTTP Retry with Backoff**: Resilient external API calls\n- **Rate Limiting**: Memory or Redis store for distributed deployments\n- **Configurable Timeouts**: Fine-tune initialization and shutdown timeouts for production environments\n\n**[Advanced Configuration →](docs/CONFIGURATION.md)**\n\n---\n\n## 🏗️ Architecture\n\n### Technology Stack\n\n- **Web Framework**: [Gin](https://gin-gonic.com/) - Fast HTTP router\n- **Templates**: [templ](https://templ.guide/) - Type-safe HTML templating\n- **ORM**: [GORM](https://gorm.io/) - Database abstraction\n- **Database**: SQLite (default) / PostgreSQL\n- **Sessions**: Encrypted cookies with [gin-contrib/sessions](https://github.com/gin-contrib/sessions)\n- **JWT**: [golang-jwt/jwt](https://github.com/golang-jwt/jwt)\n\n### Project Structure\n\n```txt\nauthgate/\n├── config/          # Configuration management\n├── handlers/        # HTTP request handlers\n├── middleware/      # Auth, CSRF, rate limiting\n├── models/          # Database models\n├── auth/            # Authentication providers\n├── token/           # Token providers\n├── services/        # Business logic\n├── store/           # Database layer (SQLite/PostgreSQL)\n├── templates/       # Type-safe templ templates\n├── docs/            # Documentation\n├── docker/          # Docker configuration\n└── _example/\n    ├── (Device Code Flow CLI → github.com/go-authgate/device-cli)\n    └── (Authorization Code Flow CLI → github.com/go-authgate/oauth-cli)\n```\n\n**[Architecture Deep Dive →](docs/ARCHITECTURE.md)**\n\n---\n\n## 🚀 Deployment\n\n### Docker Deployment\n\n```bash\n# Build image\ndocker build -f docker/Dockerfile -t authgate .\n\n# Run container\ndocker run -d \\\n  --name authgate \\\n  --restart unless-stopped \\\n  -p 8080:8080 \\\n  -v authgate-data:/app/data \\\n  -e JWT_SECRET=$(openssl rand -hex 32) \\\n  -e SESSION_SECRET=$(openssl rand -hex 32) \\\n  -e BASE_URL=https://auth.yourdomain.com \\\n  authgate:latest\n```\n\n### Production Deployment\n\n- **Binary Deployment**: Systemd service with security hardening\n- **Docker Compose**: Multi-container setup with health checks\n- **Reverse Proxy**: Nginx/Caddy with SSL/TLS\n- **Cloud Platforms**: Fly.io, AWS, GCP, Azure\n\n**[Complete Deployment Guide →](docs/DEPLOYMENT.md)**\n\n---\n\n## 🔒 Security\n\n### Production Checklist\n\n- [ ] Generate strong JWT and session secrets (32+ bytes)\n- [ ] Set secure admin password\n- [ ] Enable HTTPS (use reverse proxy)\n- [ ] Configure rate limiting\n- [ ] Enable audit logging\n- [ ] Set up regular database backups\n- [ ] Review security best practices\n\n**[Full Security Guide →](docs/SECURITY.md)**\n\n### What AuthGate Protects\n\n- ✅ Client secret exposure in distributed apps\n- ✅ Phishing attacks (authorization on trusted domain)\n- ✅ Replay attacks (single-use device codes)\n- ✅ Token tampering (JWT signature verification)\n- ✅ Brute force attacks (rate limiting)\n- ✅ Session hijacking (encrypted cookies, CSRF protection)\n\n---\n\n## 📊 Performance\n\n### Benchmarks (Reference)\n\n**Hardware**: 2-core CPU, 4GB RAM, SSD\n\n| Metric             | SQLite | PostgreSQL |\n| ------------------ | ------ | ---------- |\n| Requests/sec       | ~500   | ~2000      |\n| Avg Response Time  | 20ms   | 5ms        |\n| P95 Response Time  | 50ms   | 15ms       |\n| Concurrent Devices | \u003c 1000 | \u003e 1000     |\n\n### Scalability\n\n- **SQLite**: Suitable for \u003c 1000 concurrent devices, single-instance deployments\n- **PostgreSQL**: Recommended for production, supports horizontal scaling\n- **Multi-Pod**: Use PostgreSQL + Redis for rate limiting and user cache across pods (`RATE_LIMIT_STORE=redis`, `USER_CACHE_TYPE=redis` or `redis-aside`). Note: `redis-aside` requires Redis \u003e= 7.0.\n\n**[Performance Guide →](docs/PERFORMANCE.md)**\n\n---\n\n## 🔧 Development\n\n### Build from Source\n\n```bash\n# Build binary\nmake build\n\n# Run tests\nmake test\n\n# Run linter\nmake lint\n\n# Cross-compile for Linux\nmake build_linux_amd64\nmake build_linux_arm64\n```\n\n### Extending AuthGate\n\n- Add custom OAuth clients\n- Implement custom authentication providers\n- Add new endpoints\n- Customize web UI templates\n\n**[Development Guide →](docs/DEVELOPMENT.md)**\n\n---\n\n## ❓ FAQ\n\n### Q: Why not use OAuth password grant?\n\nPassword grant requires users to enter credentials directly into your app, training users to trust third parties with passwords (security anti-pattern). Device flow keeps credentials on the trusted authorization server.\n\n### Q: Can I use this in production?\n\nYes! Follow the [Security Checklist](docs/SECURITY.md#production-deployment-checklist) and harden your deployment. AuthGate includes production features like audit logging, rate limiting, and health checks.\n\n### Q: How do I add user registration?\n\nImplement custom registration handlers. See [Development Guide](docs/DEVELOPMENT.md#extending-the-server).\n\n### Q: Does it support refresh tokens?\n\nYes! AuthGate fully supports [RFC 6749][rfc6749] refresh tokens with two modes:\n\n- **Fixed Mode** (default): Reusable tokens, perfect for multi-device\n- **Rotation Mode**: High-security one-time-use tokens\n\n### Q: How do users revoke device access?\n\n- Web UI: Visit `/account/sessions`\n- CLI/API: Call `POST /oauth/revoke`\n- Bulk action: \"Revoke All\" button\n\n### Q: Does it support Authorization Code Flow for web apps?\n\nYes. Enable it per-client in **Admin → OAuth Clients**. Public clients (SPAs, mobile apps) use PKCE instead of a client secret.\n\n**[Authorization Code Flow Guide →](docs/AUTHORIZATION_CODE_FLOW.md)**\n\n### Q: Does it support machine-to-machine (M2M) authentication?\n\nYes. AuthGate implements the **Client Credentials Grant** (RFC 6749 §4.4) for service-to-service and daemon authentication without a user context:\n\n1. Create a **confidential** OAuth client and enable \"Client Credentials Flow\" in Admin\n2. Your service POSTs to `/oauth/token` with `grant_type=client_credentials` and HTTP Basic Auth\n3. Receive an access token — no user login required, no refresh token\n\n**[Client Credentials Flow Guide →](docs/CLIENT_CREDENTIALS_FLOW.md)**\n\n**[More FAQs →](docs/TROUBLESHOOTING.md#frequently-asked-questions-faq)**\n\n---\n\n## 🤝 Contributing\n\nContributions are welcome! Please:\n\n1. Fork the repository\n2. Create a feature branch\n3. Write tests for new features\n4. Run `make fmt \u0026\u0026 make lint \u0026\u0026 make test`\n5. Submit a Pull Request\n\n---\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n---\n\n## 📚 References\n\n- [RFC 8628 - OAuth 2.0 Device Authorization Grant][rfc8628]\n- [RFC 6749 - OAuth 2.0 Authorization Framework][rfc6749]\n- [RFC 7636 - PKCE for OAuth Public Clients][rfc7636]\n- [RFC 7009 - OAuth 2.0 Token Revocation][rfc7009]\n- [RFC 8725 - JWT Best Practices][rfc8725]\n- [RFC 8414 - OAuth 2.0 Authorization Server Metadata][rfc8414]\n- [RFC 9700 - Best Current Practice for OAuth 2.0 Security][rfc9700]\n- [OpenID Connect Core 1.0][oidccore]\n\n---\n\n## 🙏 Acknowledgments\n\nBuilt with:\n\n- [Gin Web Framework](https://gin-gonic.com/)\n- [GORM](https://gorm.io/)\n- [templ](https://templ.guide/)\n- [golang-jwt](https://github.com/golang-jwt/jwt)\n\n---\n\n**Need Help?** Check the [Troubleshooting Guide](docs/TROUBLESHOOTING.md) or open an issue on GitHub.\n\n**Ready to Deploy?** Start with the [Deployment Guide](docs/DEPLOYMENT.md).\n\n\u003c!-- RFC link definitions --\u003e\n\n[rfc8628]: https://datatracker.ietf.org/doc/html/rfc8628\n[rfc6749]: https://datatracker.ietf.org/doc/html/rfc6749\n[rfc7636]: https://datatracker.ietf.org/doc/html/rfc7636\n[rfc7009]: https://datatracker.ietf.org/doc/html/rfc7009\n[rfc8725]: https://datatracker.ietf.org/doc/html/rfc8725\n[rfc8414]: https://datatracker.ietf.org/doc/html/rfc8414\n[rfc9700]: https://datatracker.ietf.org/doc/html/rfc9700\n[oidccore]: https://openid.net/specs/openid-connect-core-1_0.html\n","funding_links":["https://www.paypal.me/appleboy46"],"categories":["Authentication and Authorization"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgo-authgate%2Fauthgate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgo-authgate%2Fauthgate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgo-authgate%2Fauthgate/lists"}