Awesome Go

authgate

CategoryAuthentication and Authorization
SubcategoryAuthentication and Authorization
Stars0

A lightweight OAuth 2.0 Authorization Server supporting Device Authorization Grant ([RFC 8628](https://datatracker.ietf.org/doc/html/rfc8628)), Authorization Code Flow with PKCE ([RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749) + [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636)), and Client Credentials Grant for machine-to-machine authentication

About authgate

This large README is shown as a plain-text preview. Read the full README at the source

# AuthGate

> 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

[![Security Scanning](https://github.com/go-authgate/authgate/actions/workflows/security.yml/badge.svg)](https://github.com/go-authgate/authgate/actions/workflows/security.yml)
[![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)
[![Go Report Card](https://goreportcard.com/badge/github.com/go-authgate/authgate)](https://goreportcard.com/report/github.com/go-authgate/authgate)
[![codecov](https://codecov.io/gh/go-authgate/authgate/graph/badge.svg?token=z0Eq9k5Vwi)](https://codecov.io/gh/go-authgate/authgate)
[![Go Reference](https://pkg.go.dev/badge/github.com/go-authgate/authgate.svg)](https://pkg.go.dev/github.com/go-authgate/authgate)
[![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

## Table of Contents

- [AuthGate](#authgate)
  - [Table of Contents](#table-of-contents)
  - [Why AuthGate?](#why-authgate)
    - [The Enterprise Case for AuthGate](#the-enterprise-case-for-authgate)
      - [1. Fragmented authentication โ€” every service re-inventing LDAP integration](#1-fragmented-authentication--every-service-re-inventing-ldap-integration)
      - [2. No token lifecycle management โ€” tokens issued, never tracked or revoked](#2-no-token-lifecycle-management--tokens-issued-never-tracked-or-revoked)
      - [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)
  - [โœจ Key Features](#-key-features)
  - [๐Ÿš€ Quick Start](#-quick-start)
    - [Prerequisites](#prerequisites)
    - [Installation](#installation)
    - [Run the Server](#run-the-server)
    - [Test with Example CLI](#test-with-example-cli)
  - [๐Ÿ“– Documentation](#-documentation)
    - [Getting Started](#getting-started)
    - [Development](#development)
    - [Operations](#operations)
    - [Advanced Topics](#advanced-topics)
  - [๐ŸŽฏ How It Works](#-how-it-works)
    - [Device Code Flow (RFC 8628) โ€” for CLI / IoT](#device-code-flow-rfc-8628--for-cli--iot)
    - [Authorization Code Flow (RFC 6749) โ€” for Web / Mobile](#authorization-code-flow-rfc-6749--for-web--mobile)
    - [Client Credentials Grant (RFC 6749 ยง4.4) โ€” for Machine-to-Machine](#client-credentials-grant-rfc-6749-44--for-machine-to-machine)
  - [๐ŸŽจ User Interface](#-user-interface)
    - [Login \& Authorization Flow](#login--authorization-flow)
    - [Session Management](#session-management)
  - [โš™๏ธ Configuration](#๏ธ-configuration)
    - [Basic Configuration (.env)](#basic-configuration-env)
    - [Advanced Features](#advanced-features)
  - [๐Ÿ—๏ธ Architecture](#๏ธ-architecture)
    - [Technology Stack](#technology-stack)
    - [Project Structure](#project-structure)
  - [๐Ÿš€ Deployment](#-deployment)
    - [Docker Deployment](#docker-deployment)
    - [Production Deployment](#production-deployment)
  - [๐Ÿ”’ Security](#-security)
    - [Production Checklist](#production-checklist)
    - [What AuthGate Protects](#what-authgate-protects)
  - [๐Ÿ“Š Performance](#-performance)
    - [Benchmarks (Reference)](#benchmarks-reference)
    - [Scalability](#scalability)
  - [๐Ÿ”ง Development](#-development)
    - [Build from Source](#build-from-source)
    - [Extending AuthGate](#extending-authgate)
  - [โ“ FAQ](#-faq)
    - [Q: Why not use OAuth password grant?](#q-why-not-use-oauth-password-grant)
    - [Q: Can I use this in production?](#q-can-i-use-this-in-production)
    - [Q: How do I add user registration?](#q-how-do-i-add-user-registration)
    - [Q: Does it support refresh tokens?](#q-does-it-support-refresh-tokens)
    - [Q: How do users revoke device access?](#q-how-do-users-revoke-device-access)
    - [Q: Does it support Authorization Code Flow for web apps?](#q-does-it-support-authorization-code-flow-for-web-apps)
    - [Q: Does it support machine-to-machine (M2M) authentication?](#q-does-it-support-machine-to-machine-m2m-authentication)
  - [๐Ÿค Contributing](#-contributing)
  - [๐Ÿ“„ License](#-license)
  - [๐Ÿ“š References](#-references)
  - [๐Ÿ™ Acknowledgments](#-acknowledgments)

---

## Why AuthGate?

Modern 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.

AuthGate 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.

**Perfect for:**

- ๐Ÿ–ฅ๏ธ CLI tools (like `gh`, `aws-cli`) โ€” **Device Code Flow**
- ๐Ÿ“บ Smart TVs, IoT devices, gaming consoles โ€” **Device Code Flow**
- ๐ŸŒ Web applications with server-side backends โ€” **Authorization Code Flow (confidential)**
- ๐Ÿ“ฑ Single-page apps and mobile apps โ€” **Authorization Code Flow + PKCE (public)**
- ๐Ÿค– CI/CD pipelines and automation scripts โ€” **Device Code Flow** or **Client Credentials**
- โš™๏ธ Microservices and server-to-server APIs โ€” **Client Credentials Grant**
- ๐Ÿข 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
- ๐Ÿ”‘ 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
- ๐Ÿ” **Security & compliance teams** โ€” comprehensive audit logs of every authentication, token, and admin event with filtering and CSV export (`/admin/audit`), satisfying audit and regulatory requirements

### The Enterprise Case for AuthGate

#### 1. Fragmented authentication โ€” every service re-inventing LDAP integration

**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:

- Every team reinvents password validation, hashing, and policy enforcement.
- LDAP credentials and bind passwords are scattered across codebases.
- Any LDAP schema change or credential rotation forces simultaneous updates and redeployments across all services.
- There is no single, consistent login record across the organisation for audit purposes.

**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:

- Outward-facing: standard OAuth 2.0 APIs (Device Code, PKCE, Client Credentials).
- Inward-facing: centralised handling of LDAP, GitHub, Microsoft, and other identity sources.
- New services register as OAuth clients and never touch LDAP directly.

#### 2. No token lifecycle management โ€” tokens issued, never tracked or revoked

**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?_

- No central record of issued tokens or active sessions.
- No refresh token rotation, expiry policy, or revocation capability.
- No audit trail: who logged in, when, from where, and which token was used?
- During a security incident, there is no fast path to revoke a token, trace its origin, or force a platform-wide re-login.

**How AuthGate helps:** Full token lifecycle management out of the box:

- Users self-serve at `/account/sessions` and `/account/authorizations` to inspect and revoke active sessions and per-app grants.
- Admins can force all users of any client to re-authenticate with a single action.
- Complete **Audit Trails** at `/admin/audit` with CSV export satisfy incident investigation and compliance requirements.

#### 3. Service owners have no visibility or control over who is using their service

**The problem:** Without a centralised authorisation layer, service owners cannot answer basic operational questions:

- Which users currently have access to this service?
- When was their authorisation granted, and when does it expire?
- What scopes were approved, and can they be narrowed?
- How do I produce a login history, IP list, and token scope report for an audit?

**How AuthGate helps:** A unified OAuth client management console gives every service owner full **visibility**, **control**, and **auditability**:

- Configure client scopes, redirect URIs, token TTLs, and user authorisation records in one place.
- View all token activity for a service in real time.
- Revoke any user's authorisation instantly.
- Respond to audits and security requests without digging through disparate system logs.

---

## โœจ Key Features

- **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
- **OIDC ID Token & UserInfo**: Issues a signed `id_token` (OIDC Core 1.0) alongside the access token when `openid` scope is granted. Supports `nonce`, `at_hash`, and scope-gated profile/email claims. Includes `/.well-known/openid-configuration` discovery, `/.well-known/jwks.json` (JWKS), and `/oauth/userinfo` endpoints.
- **Flexible JWT Signing**: Supports HS256 (symmetric), RS256 (RSA), and ES256 (ECDSA P-256) signing algorithms. Asymmetric keys enable resource servers to verify tokens via the JWKS endpoint without sharing secrets.
- **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
- **Security First**: Rate limiting, audit logging, CSRF protection, PKCE enforcement, and session management built-in
- **Production Ready**: Built-in monitoring with Prometheus metrics, health checks, comprehensive audit trails, and graceful shutdown with configurable timeouts
- **Zero Dependencies**: Single static binary with SQLite embedded, or use PostgreSQL for scale
- **Multi-Auth Support**: Local authentication, external HTTP API, OAuth providers (GitHub, Gitea, Microsoft)
- **Flexible Deployment**: Docker-ready, cloud-friendly, runs anywhere with context-aware lifecycle management
- **Token Management**: Fixed and rotation refresh token modes, web UI for session management
- **Dynamic Client Registration ([RFC 7591][rfc7591])**: Programmatic client registration with admin approval workflow, protected by optional initial access token
- **Token Introspection ([RFC 7662][rfc7662])**: RFC-compliant token metadata inspection with client credential authentication

---

## ๐Ÿš€ Quick Start

### Prerequisites

- Go 1.25 or higher
- Make (optional, but recommended)

### Installation

```bash
# Clone repository
git clone <repository-url>
cd authgate

# Copy environment configuration
cp .env.example .env

# Generate strong secrets
echo "JWT_SECRET=$(openssl rand -hex 32)" >> .env
echo "SESSION_SECRET=$(openssl rand -hex 32)" >> .env

# Build the server
make build
```

### Run the Server

```bash
# Start server
./bin/authgate server

# Or with Docker
docker run -d \
  --name authgate \
  -p 8080:8080 \
  -v authgate-data:/app/data \
  -e JWT_SECRET=$(openssl rand -hex 32) \
  -e SESSION_SECRET=$(openssl rand -hex 32) \
  -e BASE_URL=http://localhost:8080 \
  authgate:latest
```

Server starts on `http://localhost:8080`

**Important:** On first run, credentials are written to `authgate-credentials.txt` (mode 0600). Note the `client_id` from this file - you'll need it for the CLI example. Delete the file after retrieving the credentials.

### Test with Example CLI

Two example CLIs are available. Each demonstrates a different OAuth 2.0 flow.

**Device Code Flow** ([github.com/go-authgate/device-cli](https://github.com/go-authgate/device-cli)) โ€” for headless environments:

```bash
git clone https://github.com/go-authgate/device-cli
cd device-cli

# Configure client
cp .env.example .env
nano .env  # Add CLIENT_ID from authgate-credentials.txt

# Run the CLI
go run main.go
```

**Authorization Code Flow** ([github.com/go-authgate/oauth-cli](https://github.com/go-authgate/oauth-cli)) โ€” for apps that can open a browser:

```bash
git clone https://github.com/go-authgate/oauth-cli
cd oauth-cli

# Configure client
cp .env.example .env
nano .env  # Add CLIENT_ID (and CLIENT_SECRET for confidential clients)

# Run the CLI
go run .
```

The 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**.

**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.

---

## ๐Ÿ“– Documentation

### Getting Started

- **[Quick Start](#-quick-start)** - Get up and running in 5 minutes
- **[Configuration Guide](docs/CONFIGURATION.md)** - Environment variables, secrets, OAuth setup, rate limiting
- **[Deployment Guide](docs/DEPLOYMENT.md)** - Production deployment with Docker, systemd, Nginx, cloud platforms

### Development

- **[Architecture Guide](docs/ARCHITECTURE.md)** - System design, flow diagrams, database schema
- **[Development Guide](docs/DEVELOPMENT.md)** - Building, testing, and extending AuthGate

### Operations

- **[Monitoring Guide](docs/MONITORING.md)** - Health checks, metrics, audit logging, alerting
- **[Prometheus Metrics](docs/METRICS.md)** - Metrics endpoint, authentication, Grafana dashboards
- **[Security Guide](docs/SECURITY.md)** - Production checklist, threat model, secrets management
- **[Troubleshooting](docs/TROUBLESHOOTING.md)** - Common issues, debug mode, FAQ

### Advanced Topics

- **[Device Code Flow Guide](docs/DEVICE_CODE_FLOW.md)** - CLI and IoT authentication, polling, token lifecycle, Go implementation
- **[Authorization Code Flow Guide](docs/AUTHORIZATION_CODE_FLOW.md)** - Auth Code Flow, PKCE, user consent, admin controls
- **[Client Credentials Flow Guide](docs/CLIENT_CREDENTIALS_FLOW.md)** - Machine-to-machine authentication, M2M token management
- **[JWT Verification Guide](docs/JWT_VERIFICATION.md)** - Verify tokens at resource servers using JWKS public keys (RS256/ES256)
- **[OAuth Setup Guide](docs/OAUTH_SETUP.md)** - GitHub, Gitea, Microsoft Entra ID integration
- **[Rate Limiting Guide](docs/RATE_LIMITING.md)** - Protect against brute force and API abuse
- **[Performance Guide](docs/PERFORMANCE.md)** - Scalability, optimization, benchmarks
- **[Use Cases](docs/USE_CASES.md)** - Real-world examples and code samples

---

## ๐ŸŽฏ How It Works

AuthGate supports three OAuth 2.0 grant types.

### Device Code Flow ([RFC 8628][rfc8628]) โ€” for CLI / IoT

```mermaid
sequenceDiagram
    participant CLI as CLI Tool
    participant AuthGate as AuthGate Server
    participant User as User (Browser)

    CLI->>AuthGate: 1. Request device code
    AuthGate-->>CLI: device_code + user_code + URL

    Note over CLI: Display: "Visit URL, Enter code"

    User->>AuthGate: 2. Visit URL, login, enter code
    AuthGate-->>User: โœ… Success

    CLI->>AuthGate: 3. Poll for token
    AuthGate-->>CLI: access_token + refresh_token
```

**[Device Code Flow Guide โ†’](docs/DEVICE_CODE_FLOW.md)**

### Authorization Code Flow ([RFC 6749][rfc6749]) โ€” for Web / Mobile

```mermaid
sequenceDiagram
    participant App as Web/Mobile App
    participant Browser as Browser
    participant AuthGate as AuthGate Server

    App->>Browser: 1. Redirect to /oauth/authorize
    Browser->>AuthGate: Login + Consent page
    AuthGate->>Browser: 302 redirect_uri?code=XXXXX
    Browser->>App: code delivered to callback
    App->>AuthGate: 2. POST /oauth/token (code + secret or PKCE)
    AuthGate-->>App: access_token + refresh_token [+ id_token if openid scope]
```

**[Authorization Code Flow Guide โ†’](docs/AUTHORIZATION_CODE_FLOW.md)**

### Client Credentials Grant ([RFC 6749][rfc6749] ยง4.4) โ€” for Machine-to-Machine

```mermaid
sequenceDiagram
    participant Svc as Service / Daemon
    participant AuthGate as AuthGate Server

    Svc->>+AuthGate: POST /oauth/token<br/>grant_type=client_credentials<br/>client_id + client_secret (Basic Auth)
    AuthGate-->>-Svc: access_token (no refresh token)

    Note over Svc: Token stored in memory<br/>re-requested when expired
```

- Requires a **confidential client** with `Client Credentials Flow` enabled in admin
- No user involved โ€” authenticates the client application itself
- No refresh token is issued; the client simply requests a new token when the current one expires
- Scope can be restricted per-request (must be a subset of the client's registered scopes)
- `openid` and `offline_access` scopes are not permitted (user-centric OIDC scopes)

**[Client Credentials Flow Guide โ†’](docs/CLIENT_CREDENTIALS_FLOW.md)**

**Key Endpoints:**

| Endpoint                            | Method   | Purpose                                                                                    |
| ----------------------------------- | -------- | ------------------------------------------------------------------------------------------ |
| `/.well-known/openid-configuration` | GET      | OIDC Discovery metadata                                                                    |
| `/.well-known/jwks.json`           | GET      | JWKS public keys for RS256/ES256 verification (RFC 7517)                                   |
| `/oauth/device/code`                | POST     | Request device code (CLI)                                                                  |
| `/oauth/authorize`                  | GET      | Authorization consent page (web apps)                                                      |
| `/oauth/authorize`                  | POST     | Submit consent decision                                                                    |
| `/oauth/token`                      | POST     | Token endpoint: `device_code`, `authorization_code`, `refresh_token`, `client_credentials` |
| `/oauth/tokeninfo`                  | GET      | Verify token validity                                                                      |
| `/oauth/userinfo`                   | GET/POST | OIDC UserInfo โ€” profile claims for token owner                                             |
| `/oauth/revoke`                     | POST     | Revoke tokens ([RFC 7009][rfc7009])                                                        |
| `/oauth/register`                   | POST     | Dynamic client registration ([RFC 7591][rfc7591])                                          |
| `/oauth/introspect`                 | POST     | Token introspection ([RFC 7662][rfc7662])                                                  |
| `/device`                           | GET      | Device code entry page (browser)                                                           |
| `/account/sessions`                 | GET      | Manage active token sessions                                                               |

Frequently Asked Questions

What is authgate?

authgate is a Authentication and Authorization library for the Go programming language. A lightweight OAuth 2.0 Authorization Server supporting Device Authorization Grant ([RFC 8628](https://datatracker.ietf.org/doc/html/rfc8628)), Authorization Code Flow with PKCE ([RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749) + [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636)), and Client Credentials Grant for machine-to-machine authentication

How do I install authgate?

Install authgate with the Go module system using `go get go-authgate/authgate`. Check the repository for the current installation instructions.

What category does authgate belong to?

authgate is listed under Authentication and Authorization, specifically Authentication and Authorization.

โ† Back to Authentication and Authorization