### Setup Redis for Development Source: https://github.com/go-authgate/authgate/blob/main/docs/RATE_LIMITING.md Local Redis setup using Docker. ```bash # Docker docker run -d --name redis -p 6379:6379 redis:7-alpine # Environment REDIS_ADDR=localhost:6379 ``` -------------------------------- ### Clone and Run Go Device CLI Example Source: https://github.com/go-authgate/authgate/blob/main/docs/DEVICE_CODE_FLOW.md This demonstrates how to clone the `go-authgate/device-cli` repository, configure it by copying the environment file and adding your `CLIENT_ID`, and then run the example. ```bash git clone https://github.com/go-authgate/device-cli cd device-cli cp .env.example .env # Add CLIENT_ID from authgate-credentials.txt go run main.go ``` -------------------------------- ### Install Dependencies Source: https://github.com/go-authgate/authgate/blob/main/docs/DEVELOPMENT.md Commands to manage Go modules. ```bash # Download Go modules go mod download # Verify dependencies go mod verify ``` -------------------------------- ### Start the AuthGate Server Source: https://github.com/go-authgate/authgate/blob/main/internal/templates/docs/getting-started.md Initializes the server and generates default credentials. ```bash ./authgate server ``` -------------------------------- ### Run Development Server Source: https://github.com/go-authgate/authgate/blob/main/docs/DEVELOPMENT.md Commands to start the server in various modes. ```bash # Run directly with Go go run . server # Or build and run make build ./bin/authgate server # Enable debug mode GIN_MODE=debug ./bin/authgate server ``` -------------------------------- ### Configure Environment Source: https://github.com/go-authgate/authgate/blob/main/docs/DEVELOPMENT.md Setup for local development environment variables. ```bash # Copy environment template cp .env.example .env # Edit configuration nano .env ``` ```bash SERVER_ADDR=:8080 BASE_URL=http://localhost:8080 JWT_SECRET=dev-secret-change-in-production SESSION_SECRET=dev-session-secret DATABASE_DSN=oauth.db ``` -------------------------------- ### Install and Configure AuthGate Source: https://github.com/go-authgate/authgate/blob/main/README.md Commands to clone the repository, set up environment variables, and build the server binary. ```bash # Clone repository git clone 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 ``` -------------------------------- ### Setup Redis for Production Source: https://github.com/go-authgate/authgate/blob/main/docs/RATE_LIMITING.md Configuration for production Redis clusters. ```bash REDIS_ADDR=redis-cluster.prod.example.com:6379 REDIS_PASSWORD=your-strong-password REDIS_DB=1 # Use dedicated database ``` -------------------------------- ### Deploy CLI Authentication Flow Source: https://github.com/go-authgate/authgate/blob/main/docs/USE_CASES.md Example output for a CLI-based device authentication process. ```bash $ myapp-cli deploy ๐Ÿ” Authentication Required Visit: https://auth.yourplatform.com/device Enter code: ABCD-1234 Waiting for authorization... โœ… Authentication successful! Deploying application... ``` -------------------------------- ### Fly.io CLI Installation and Authentication Source: https://github.com/go-authgate/authgate/blob/main/docs/DEPLOYMENT.md Commands to install the `flyctl` CLI tool and authenticate with your Fly.io account. Ensure you are logged in before proceeding with deployment. ```bash curl -L https://fly.io/install.sh | sh flyctl auth login ``` -------------------------------- ### Example Authorization Request with OIDC Source: https://github.com/go-authgate/authgate/blob/main/docs/AUTHORIZATION_CODE_FLOW.md Demonstrates an example authorization request URL including OpenID Connect parameters like `scope`, `nonce`, `code_challenge`, and `code_challenge_method`. ```http GET /oauth/authorize? client_id=550e8400-e29b-41d4-a716-446655440000 &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback &response_type=code &scope=openid%20profile%20email &state=abc123xyz &nonce=random-nonce-value &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM &code_challenge_method=S256 ``` -------------------------------- ### GORM Debug Output Example Source: https://github.com/go-authgate/authgate/blob/main/docs/TROUBLESHOOTING.md Example of SQL query logging when GORM debug mode is enabled. ```sql [2026-02-08 10:00:00] SELECT * FROM users WHERE username = 'admin' LIMIT 1 ``` -------------------------------- ### Display Instructions Source: https://github.com/go-authgate/authgate/blob/main/internal/templates/docs/device-flow.md Example output to present to the user for manual entry into a browser. ```text Open https://your-authgate/device in your browser. Enter code: WXYZ-1234 Waiting for authorization... ``` -------------------------------- ### Start AuthGate Server Source: https://github.com/go-authgate/authgate/blob/main/docs/CONFIGURATION.md Command to launch the AuthGate server using the default memory store configuration. ```bash # Default configuration - rate limiting enabled with memory store ./bin/authgate server ``` -------------------------------- ### Gin Debug Output Example Source: https://github.com/go-authgate/authgate/blob/main/docs/TROUBLESHOOTING.md Example of detailed logging output when Gin debug mode is enabled, showing request routing and handling. ```text [GIN-debug] GET /health --> main.healthCheck (3 handlers) [GIN-debug] POST /oauth/device/code --> handlers.(*DeviceHandler).RequestDeviceCode [GIN-debug] Listening and serving HTTP on :8080 [GIN] 2026/02/08 - 10:00:00 | 200 | 1.234ms | 192.168.1.1 | GET "/health" ``` -------------------------------- ### Run AuthGate Server Source: https://github.com/go-authgate/authgate/blob/main/README.md Methods to start the AuthGate server using the compiled binary or a Docker container. ```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 ``` -------------------------------- ### Configure Multi-Pod Redis Deployment Source: https://github.com/go-authgate/authgate/blob/main/docs/CONFIGURATION.md Example configurations for scaling AuthGate across multiple pods using Redis or Redis-aside. ```bash # 2โ€“5 pods: Redis shared cache USER_CACHE_TYPE=redis REDIS_ADDR=redis-service:6379 # 5+ pods or DDoS protection: redis-aside with client-side caching USER_CACHE_TYPE=redis-aside REDIS_ADDR=redis-service:6379 USER_CACHE_CLIENT_TTL=30s USER_CACHE_SIZE_PER_CONN=32 # Adjust based on available memory per pod ``` -------------------------------- ### Deploy Single Instance with Docker Source: https://github.com/go-authgate/authgate/blob/main/docs/RATE_LIMITING.md Example docker-compose configuration for a single AuthGate instance. ```yaml # docker-compose.yml services: authgate: image: authgate:latest environment: - ENABLE_RATE_LIMIT=true - RATE_LIMIT_STORE=memory # Default - LOGIN_RATE_LIMIT=5 ``` -------------------------------- ### Setup Redis High Availability Source: https://github.com/go-authgate/authgate/blob/main/docs/RATE_LIMITING.md Configuration for Redis Sentinel high availability. ```bash # Use Redis Sentinel for HA REDIS_ADDR=sentinel-1:26379,sentinel-2:26379,sentinel-3:26379 REDIS_PASSWORD=your-password ``` -------------------------------- ### User Authentication Prompt Source: https://github.com/go-authgate/authgate/blob/main/docs/DEVICE_CODE_FLOW.md Display these instructions to the user in the CLI to guide them through the browser-based authentication process. ```text To sign in, visit: https://auth.example.com/device And enter the code: ABCD-EFGH Waiting for authorization... ``` -------------------------------- ### Verify Token using /oauth/tokeninfo API Source: https://github.com/go-authgate/authgate/blob/main/docs/CLIENT_CREDENTIALS_FLOW.md This example shows how to verify an access token by calling the `/oauth/tokeninfo` endpoint. This is useful for resource servers to check token validity and claims. ```bash curl -X GET https://your-authgate-domain.com/oauth/tokeninfo \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` -------------------------------- ### Manage Systemd Service Source: https://github.com/go-authgate/authgate/blob/main/docs/DEPLOYMENT.md Commands to reload, enable, start, and monitor the AuthGate service. ```bash # Reload systemd sudo systemctl daemon-reload # Enable service to start on boot sudo systemctl enable authgate # Start service sudo systemctl start authgate # Check status sudo systemctl status authgate # View logs sudo journalctl -u authgate -f ``` -------------------------------- ### Querying Metrics with Authentication Source: https://github.com/go-authgate/authgate/blob/main/docs/METRICS.md Examples for accessing the metrics endpoint with and without Bearer Token authentication, plus a command to generate a secure token. ```bash # Without authentication (default) curl http://localhost:8080/metrics # With Bearer Token enabled curl -H "Authorization: Bearer your-secret-bearer-token" \ http://localhost:8080/metrics # Generate a strong random token (recommended for production) openssl rand -base64 48 ``` -------------------------------- ### Accessing AuthGate Metrics via CLI Source: https://github.com/go-authgate/authgate/blob/main/docs/METRICS.md Commands to start the server and query the metrics endpoint, including filtering for specific metric prefixes. ```bash # Start the server ./bin/authgate server # Access metrics endpoint curl http://localhost:8080/metrics # Filter for custom metrics curl http://localhost:8080/metrics | grep -E "^(oauth|auth|http_request|session)" ``` -------------------------------- ### Audit API Queries Source: https://github.com/go-authgate/authgate/blob/main/docs/MONITORING.md Examples for interacting with the audit API to retrieve logs, export data, and view statistics. ```bash curl -s "http://localhost:8080/admin/audit/api?event_type=AUTHENTICATION_FAILURE&since=24h" \ -H "Cookie: session=..." | jq . ``` ```bash curl "http://localhost:8080/admin/audit/export?severity=CRITICAL" \ -H "Cookie: session=..." -o critical-events.csv ``` ```bash curl -s "http://localhost:8080/admin/audit/api/stats" \ -H "Cookie: session=..." | jq . ``` -------------------------------- ### Add New OAuth Provider in Go Source: https://github.com/go-authgate/authgate/blob/main/docs/OAUTH_SETUP.md Example of how to add a new OAuth provider (GitLab) by creating a new provider function and initializing it. ```go func NewGitLabProvider(cfg OAuthProviderConfig) *OAuthProvider { return &OAuthProvider{ provider: "gitlab", config: &oauth2.Config{ ClientID: cfg.ClientID, ClientSecret: cfg.ClientSecret, RedirectURL: cfg.RedirectURL, Scopes: cfg.Scopes, Endpoint: gitlab.Endpoint, }, } } ``` ```go if cfg.GitLabOAuthEnabled { providers["gitlab"] = auth.NewGitLabProvider(...) } ``` -------------------------------- ### Setup CI/CD Refresh Token via Device Flow Source: https://github.com/go-authgate/authgate/blob/main/docs/USE_CASES.md Executes the OAuth 2.0 device authorization grant to obtain a long-lived refresh token for automated environments. ```bash #!/bin/bash # setup-ci-token.sh CLIENT_ID="cicd-client-id" AUTH_SERVER="https://auth.yourplatform.com" # Perform device flow response=$(curl -s -X POST "$AUTH_SERVER/oauth/device/code" \ -d "client_id=$CLIENT_ID") device_code=$(echo $response | jq -r '.device_code') user_code=$(echo $response | jq -r '.user_code') verification_uri=$(echo $response | jq -r '.verification_uri') interval=$(echo $response | jq -r '.interval') echo "Visit: $verification_uri" echo "Enter code: $user_code" echo "" echo "Waiting for authorization..." # Poll for token while true; do sleep $interval token_response=$(curl -s -X POST "$AUTH_SERVER/oauth/token" \ -d "grant_type=urn:ietf:params:oauth:grant-type:device_code" \ -d "device_code=$device_code" \ -d "client_id=$CLIENT_ID") error=$(echo $token_response | jq -r '.error // empty') if [ "$error" = "authorization_pending" ]; then continue elif [ -z "$error" ]; then # Success refresh_token=$(echo $token_response | jq -r '.refresh_token') echo "" echo "โœ… Authentication successful!" echo "" echo "Add this secret to your CI/CD environment:" echo "PLATFORM_REFRESH_TOKEN=$refresh_token" break else echo "Error: $error" exit 1 fi done ``` -------------------------------- ### Request Access Token using Client Credentials (JavaScript/Node.js) Source: https://github.com/go-authgate/authgate/blob/main/docs/CLIENT_CREDENTIALS_FLOW.md This Node.js example demonstrates how to get an access token using the Client Credentials grant. It uses the built-in `https` module for making the request. ```javascript const https = require('https'); const clientID = 'YOUR_CLIENT_ID'; const clientSecret = 'YOUR_CLIENT_SECRET'; const tokenURL = 'https://your-authgate-domain.com/oauth/token'; const credentials = Buffer.from(`${clientID}:${clientSecret}`).toString('base64'); const postData = 'grant_type=client_credentials&scope=read%20write'; const options = { hostname: 'your-authgate-domain.com', port: 443, path: '/oauth/token', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': `Basic ${credentials}` } }; const req = https.request(options, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log('Response Status:', res.statusCode); console.log('Response Body:', JSON.parse(data)); }); }); req.on('error', (error) => { console.error('Error:', error); }); req.write(postData); req.end(); ``` -------------------------------- ### Public Client Token Exchange with PKCE Source: https://github.com/go-authgate/authgate/blob/main/docs/AUTHORIZATION_CODE_FLOW.md Example using curl to exchange an authorization code for tokens for a public client, utilizing PKCE for enhanced security. Include the code verifier. ```bash curl -X POST https://auth.example.com/oauth/token \ -d grant_type=authorization_code \ -d code=a1b2c3d4... \ -d redirect_uri=https://app.example.com/callback \ -d client_id=550e8400-... \ -d code_verifier=your-original-verifier ``` -------------------------------- ### PromQL Label Cardinality Example Source: https://github.com/go-authgate/authgate/blob/main/docs/METRICS.md Illustrates correct and incorrect usage of labels in PromQL queries to avoid high cardinality issues. Use bounded sets of values for labels. ```promql # โŒ BAD - Unbounded cardinality http_requests_total{user_id="12345"} # โœ… GOOD - Bounded set of values http_requests_total{path="/oauth/token"} ``` -------------------------------- ### Authorization Request Examples Source: https://github.com/go-authgate/authgate/blob/main/docs/AUTHORIZATION_CODE_FLOW.md Examples of authorization requests for confidential and public clients. ```http GET /oauth/authorize? client_id=550e8400-e29b-41d4-a716-446655440000 &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback &response_type=code &scope=email%20profile &state=abc123xyz ``` ```http GET /oauth/authorize? client_id=550e8400-e29b-41d4-a716-446655440000 &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback &response_type=code &scope=email &state=abc123xyz &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM &code_challenge_method=S256 ``` -------------------------------- ### Display Device LCD Setup Screen Source: https://github.com/go-authgate/authgate/blob/main/docs/USE_CASES.md Visual representation of the setup screen displayed on an IoT device. ```text โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— โ•‘ Setup Required โ•‘ โ•‘ โ•‘ โ•‘ Visit: โ•‘ โ•‘ auth.app.com โ•‘ โ•‘ โ•‘ โ•‘ Code: WXYZ-5678 โ•‘ โ•‘ โ•‘ โ•‘ [QR Code] โ•‘ โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• ``` -------------------------------- ### Build, Test, and Lint Go Project Source: https://github.com/go-authgate/authgate/blob/main/README.md Standard make commands for building the Go AuthGate binary, running tests, and performing linting. ```bash # Build binary make build # Run tests make test # Run linter make lint ``` -------------------------------- ### Build Commands Source: https://github.com/go-authgate/authgate/blob/main/docs/DEVELOPMENT.md Instructions for compiling the application binary. ```bash # Build binary with version info (outputs to bin/authgate) make build # Build directly with Go (no version info) go build -o bin/authgate . ``` ```bash # Install binary to $GOPATH/bin make install # Now you can run from anywhere authgate server ``` ```bash # Build static binary for Linux (amd64) make build_linux_amd64 # Output: release/linux/amd64/authgate # Build static binary for Linux (arm64) make build_linux_arm64 # Output: release/linux/arm64/authgate ``` -------------------------------- ### Install Certbot and Obtain SSL Certificate Source: https://github.com/go-authgate/authgate/blob/main/docs/SECURITY.md Installs Certbot for Nginx and obtains an SSL certificate for a specified domain. Auto-renewal is configured by default. ```bash sudo apt-get install certbot python3-certbot-nginx ``` ```bash sudo certbot --nginx -d auth.yourdomain.com ``` ```bash sudo certbot renew --dry-run ``` -------------------------------- ### Certbot SSL Certificate Installation Source: https://github.com/go-authgate/authgate/blob/main/docs/DEPLOYMENT.md Steps to install Certbot and obtain an SSL certificate for your domain using the Nginx plugin. Auto-renewal is configured by default, but test it with `--dry-run`. ```bash sudo apt-get update sudo apt-get install certbot python3-certbot-nginx sudo certbot --nginx -d auth.yourdomain.com sudo certbot renew --dry-run ``` -------------------------------- ### Clone Repository Source: https://github.com/go-authgate/authgate/blob/main/docs/DEVELOPMENT.md Initial steps to download the source code. ```bash # Clone the repository git clone cd authgate ``` -------------------------------- ### GET /health Source: https://github.com/go-authgate/authgate/blob/main/README.md Performs a health check on the AuthGate server instance. ```APIDOC ## GET /health ### Description Returns the health status of the service. ### Method GET ### Endpoint /health ``` -------------------------------- ### Clone and Run Device CLI Source: https://github.com/go-authgate/authgate/blob/main/CLAUDE.md Clone the device-CLI repository, configure it with your Authgate CLIENT_ID, and run it to demonstrate the device flow. ```bash git clone https://github.com/go-authgate/device-cli cd device-cli cp .env.example .env # Add CLIENT_ID from authgate-credentials.txt go run main.go ``` -------------------------------- ### GET /admin/audit/api/stats Source: https://github.com/go-authgate/authgate/blob/main/docs/MONITORING.md Retrieves statistics and event counts for audit logs. ```APIDOC ## GET /admin/audit/api/stats ### Description Returns statistics and event counts for audit logs. ### Method GET ### Endpoint /admin/audit/api/stats ### Request Example curl -s "http://localhost:8080/admin/audit/api/stats" -H "Cookie: session=..." ``` -------------------------------- ### Build Static Binary Source: https://github.com/go-authgate/authgate/blob/main/docs/DEPLOYMENT.md Compiles the AuthGate binary for Linux with CGO disabled. ```bash # Build static binary for Linux (CGO disabled) make build_linux_amd64 # Output: release/linux/amd64/authgate ``` -------------------------------- ### Deploy Binary to Server Source: https://github.com/go-authgate/authgate/blob/main/docs/DEPLOYMENT.md Transfers the binary to the target server and sets executable permissions. ```bash # Copy binary to server scp release/linux/amd64/authgate user@server:/usr/local/bin/ # Set executable permissions ssh user@server "chmod +x /usr/local/bin/authgate" ``` -------------------------------- ### Configure AuthGate Environment Variables Source: https://github.com/go-authgate/authgate/blob/main/docs/JWT_VERIFICATION.md Set the signing algorithm and path to the private key in the AuthGate environment configuration. ```bash # For RS256 JWT_SIGNING_ALGORITHM=RS256 JWT_PRIVATE_KEY_PATH=/path/to/rsa-private.pem JWT_KEY_ID= # Optional: auto-generated from key fingerprint # For ES256 JWT_SIGNING_ALGORITHM=ES256 JWT_PRIVATE_KEY_PATH=/path/to/ec-private.pem JWT_KEY_ID= # Optional: auto-generated from key fingerprint ``` -------------------------------- ### View Version Information Source: https://github.com/go-authgate/authgate/blob/main/docs/DEVELOPMENT.md Check the current build version and metadata. ```bash # Show version ./bin/authgate -v ./bin/authgate --version # Output example: # Version: v1.0.0 # Build Time: 2026-02-08T10:00:00Z # Git Commit: abc1234 # Go Version: go1.25.0 # OS/Arch: linux/amd64 ``` -------------------------------- ### GET /account/sessions Source: https://github.com/go-authgate/authgate/blob/main/README.md Allows users to view and manage their active authentication sessions. ```APIDOC ## GET /account/sessions ### Description Lists all active sessions for the authenticated user. ### Method GET ### Endpoint /account/sessions ``` -------------------------------- ### Implement Device Code Flow in Go Source: https://context7.com/go-authgate/authgate/llms.txt Demonstrates the full device authorization flow, including code request, user prompt, and token polling with backoff logic. ```go package main import ( "encoding/json" "errors" "fmt" "net/http" "net/url" "time" ) const ( authServer = "https://auth.example.com" clientID = "550e8400-e29b-41d4-a716-446655440000" scope = "email profile" ) type DeviceCodeResponse struct { DeviceCode string `json:"device_code"` UserCode string `json:"user_code"` VerificationURI string `json:"verification_uri"` VerificationURIComplete string `json:"verification_uri_complete"` ExpiresIn int `json:"expires_in"` Interval int `json:"interval"` } type TokenResponse struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` TokenType string `json:"token_type"` ExpiresIn int `json:"expires_in"` Scope string `json:"scope"` } var ( ErrAuthorizationPending = errors.New("authorization_pending") ErrSlowDown = errors.New("slow_down") ErrExpiredToken = errors.New("expired_token") ErrAccessDenied = errors.New("access_denied") ) func requestDeviceCode() (*DeviceCodeResponse, error) { resp, err := http.PostForm(authServer+"/oauth/device/code", url.Values{ "client_id": {clientID}, "scope": {scope}, }) if err != nil { return nil, err } defer resp.Body.Close() var dc DeviceCodeResponse if err := json.NewDecoder(resp.Body).Decode(&dc); err != nil { return nil, err } return &dc, nil } func pollToken(deviceCode string) (*TokenResponse, error) { resp, err := http.PostForm(authServer+"/oauth/token", url.Values{ "grant_type": {"urn:ietf:params:oauth:grant-type:device_code"}, "device_code": {deviceCode}, "client_id": {clientID}, }) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { var t TokenResponse if err := json.NewDecoder(resp.Body).Decode(&t); err != nil { return nil, err } return &t, nil } var tokenErr struct{ Error string `json:"error"` } _ = json.NewDecoder(resp.Body).Decode(&tokenErr) switch tokenErr.Error { case "authorization_pending": return nil, ErrAuthorizationPending case "slow_down": return nil, ErrSlowDown case "expired_token": return nil, ErrExpiredToken case "access_denied": return nil, ErrAccessDenied default: return nil, fmt.Errorf("token error: %s", tokenErr.Error) } } func login() (*TokenResponse, error) { dc, err := requestDeviceCode() if err != nil { return nil, fmt.Errorf("failed to request device code: %w", err) } fmt.Printf("\nTo sign in, visit:\n\n %s\n\nAnd enter the code: %s\n\nWaiting for authorization...\n\n", dc.VerificationURI, dc.UserCode) interval := time.Duration(dc.Interval) * time.Second deadline := time.Now().Add(time.Duration(dc.ExpiresIn) * time.Second) for time.Now().Before(deadline) { time.Sleep(interval) tokens, err := pollToken(dc.DeviceCode) if err == nil { return tokens, nil } switch { case errors.Is(err, ErrAuthorizationPending): // continue polling case errors.Is(err, ErrSlowDown): interval += 5 * time.Second case errors.Is(err, ErrExpiredToken): return nil, fmt.Errorf("authorization timed out") case errors.Is(err, ErrAccessDenied): return nil, fmt.Errorf("authorization denied by user") default: return nil, err } } return nil, fmt.Errorf("authorization timed out") } func main() { tokens, err := login() if err != nil { fmt.Println("Error:", err) return } fmt.Println("Logged in! Access token:", tokens.AccessToken[:20]+"...") } ``` -------------------------------- ### Retrieve UserInfo Source: https://context7.com/go-authgate/authgate/llms.txt Get user profile claims using an access token. ```bash # Get user info curl -s https://auth.example.com/oauth/userinfo \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." # Response (depends on granted scopes): # { # "sub": "user-uuid", ``` -------------------------------- ### AuthGate Build and Development Commands Source: https://github.com/go-authgate/authgate/blob/main/CLAUDE.md Standard Makefile commands for building, running, testing, and managing the AuthGate project. ```bash # Build (IMPORTANT: make generate is required before building) make generate # Generate templ templates and Swagger docs (REQUIRED before build) make build # Build to bin/authgate with version info in LDFLAGS # Run ./bin/authgate -v # Show version information ./bin/authgate -h # Show help ./bin/authgate server # Start the OAuth server # Development make dev # Hot reload development mode (watches .go, .templ, .env, .css, .js) make generate # Compile .templ templates to Go code (REQUIRED) make swagger # Generate OpenAPI/Swagger documentation # Test & Lint make test # Run tests with coverage report (outputs coverage.txt) make coverage # View test coverage in browser make lint # Run golangci-lint (auto-installs if missing) make fmt # Format code with golangci-lint fmt # Cross-compile (outputs to release///) make build_linux_amd64 # CGO_ENABLED=0 for static binary make build_linux_arm64 # CGO_ENABLED=0 for static binary # Clean make clean # Remove bin/, release/, coverage.txt, generated templ files # Docker docker build -f docker/Dockerfile -t authgate . ``` -------------------------------- ### Test with Device Code Flow CLI Source: https://github.com/go-authgate/authgate/blob/main/README.md Steps to configure and run the 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 ``` -------------------------------- ### GET /account/authorizations Source: https://github.com/go-authgate/authgate/blob/main/docs/AUTHORIZATION_CODE_FLOW.md Retrieves a list of all applications the currently logged-in user has granted access to. ```APIDOC ## GET /account/authorizations ### Description Displays a list of all applications the logged-in user has granted access to, including authorized scopes and the grant date. ### Method GET ### Endpoint /account/authorizations ### Response #### Success Response (200) - **authorizations** (array) - List of authorized applications. ``` -------------------------------- ### GET /.well-known/openid-configuration Source: https://github.com/go-authgate/authgate/blob/main/docs/JWT_VERIFICATION.md Retrieves the OIDC configuration, including endpoints and supported signing algorithms. ```APIDOC ## GET /.well-known/openid-configuration ### Description Retrieves the OIDC configuration for the AuthGate server, allowing resource servers to discover endpoints and supported signing algorithms. ### Method GET ### Endpoint /.well-known/openid-configuration ### Response #### Success Response (200) - **issuer** (string) - The issuer URL - **jwks_uri** (string) - The URI for the JWKS endpoint - **id_token_signing_alg_values_supported** (array) - Supported signing algorithms - **token_endpoint** (string) - The OAuth token endpoint - **authorization_endpoint** (string) - The OAuth authorization endpoint - **userinfo_endpoint** (string) - The user info endpoint #### Response Example { "issuer": "https://your-authgate", "jwks_uri": "https://your-authgate/.well-known/jwks.json", "id_token_signing_alg_values_supported": ["RS256"], "token_endpoint": "https://your-authgate/oauth/token", "authorization_endpoint": "https://your-authgate/oauth/authorize", "userinfo_endpoint": "https://your-authgate/oauth/userinfo" } ``` -------------------------------- ### Migrate to Redis Store Source: https://github.com/go-authgate/authgate/blob/main/docs/RATE_LIMITING.md Steps to deploy Redis and update AuthGate configuration for production environments. ```bash kubectl apply -f redis-deployment.yaml ``` ```bash RATE_LIMIT_STORE=redis REDIS_ADDR=redis-service:6379 ``` ```bash kubectl rollout restart deployment/authgate ``` ```bash kubectl logs -f deployment/authgate | grep "Redis rate limiting configured" ``` -------------------------------- ### Clone and Run OAuth CLI Source: https://github.com/go-authgate/authgate/blob/main/docs/AUTHORIZATION_CODE_FLOW.md Steps to clone the oauth-cli repository, configure environment variables, and run the application. Ensure to fill in your CLIENT_ID and optionally CLIENT_SECRET. ```bash git clone https://github.com/go-authgate/oauth-cli cd oauth-cli cp .env.example .env # Fill in CLIENT_ID (and CLIENT_SECRET for confidential clients) go run . ``` -------------------------------- ### GET /admin/clients/:client_id/authorizations Source: https://github.com/go-authgate/authgate/blob/main/docs/AUTHORIZATION_CODE_FLOW.md Retrieves a list of all users who have granted consent to a specific OAuth client. ```APIDOC ## GET /admin/clients/:client_id/authorizations ### Description Shows every user who has granted consent to this application, including their username, email, approved scopes, and grant timestamp. ### Method GET ### Endpoint /admin/clients/:client_id/authorizations ### Parameters #### Path Parameters - **client_id** (string) - Required - The unique identifier of the OAuth client. ### Response #### Success Response (200) - **users** (array) - List of users who have authorized the client. ``` -------------------------------- ### Optimize Session Queries Source: https://github.com/go-authgate/authgate/blob/main/docs/PERFORMANCE.md Demonstrates using batch queries to avoid N+1 performance issues. ```go // Good: Batch query with WHERE IN tokenIDs := []string{"id1", "id2", "id3"} db.Preload("User").Preload("OAuthClient").Where("id IN ?", tokenIDs).Find(&tokens) // Bad: N+1 query for _, tokenID := range tokenIDs { db.Preload("User").Preload("OAuthClient").First(&token, tokenID) } ``` -------------------------------- ### Retrieve UserInfo Claims Source: https://github.com/go-authgate/authgate/blob/main/docs/ARCHITECTURE.md Example JSON response for a userinfo request with openid, profile, and email scopes. ```json { "sub": "550e8400-e29b-41d4-a716-446655440000", "name": "John Doe", "preferred_username": "johndoe", "picture": "https://example.com/avatar.jpg", "updated_at": 1708646400, "email": "john@example.com", "email_verified": false } ``` -------------------------------- ### Request Access Token using Client Credentials (Go) Source: https://github.com/go-authgate/authgate/blob/main/docs/CLIENT_CREDENTIALS_FLOW.md This Go code snippet demonstrates how to obtain an access token using the Client Credentials grant. It includes setting up the HTTP client and request, and handling the response. ```go package main import ( "encoding/base64" "fmt" "io" "net/http" "net/url" "strings" ) func main() { clientID := "YOUR_CLIENT_ID" clientSecret := "YOUR_CLIENT_SECRET" tokenURL := "https://your-authgate-domain.com/oauth/token" // Encode credentials for Basic Authentication credentials := clientID + ":" + clientSecret encodedCredentials := base64.StdEncoding.EncodeToString([]byte(credentials)) // Prepare form data formData := url.Values{} formData.Set("grant_type", "client_credentials") formData.Set("scope", "read write") // Create HTTP request req, err := http.NewRequest("POST", tokenURL, strings.NewReader(formData.Encode())) if err != nil { fmt.Println("Error creating request:", err) return } // Set headers req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Authorization", "Basic "+encodedCredentials) // Send request client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() // Read response body body, err := io.ReadAll(res.Body) if err != nil { fmt.Println("Error reading response body:", err) return } fmt.Println("Response Status:", res.Status) fmt.Println("Response Body:", string(body)) } ``` -------------------------------- ### Configure AuthGate Environment Variables Source: https://github.com/go-authgate/authgate/blob/main/docs/CONFIGURATION.md Define server, security, and database settings in a .env file. Ensure secrets are updated for production environments. ```bash # Server Configuration SERVER_ADDR=:8080 # Listen address (e.g., :8080, 0.0.0.0:8080) BASE_URL=http://localhost:8080 # Public URL for verification_uri # Security - CHANGE THESE IN PRODUCTION! JWT_SECRET=your-256-bit-secret-change-in-production # HMAC-SHA256 signing key SESSION_SECRET=session-secret-change-in-production # Cookie encryption key # Database DATABASE_DRIVER=sqlite # Database driver: "sqlite" or "postgres" DATABASE_DSN=oauth.db # Connection string (file path for SQLite, DSN for PostgreSQL) # PostgreSQL Example: # DATABASE_DRIVER=postgres # DATABASE_DSN="host=localhost user=authgate password=secret dbname=authgate port=5432 sslmode=disable" # Database Log Level # DB_LOG_LEVEL=warn # GORM log level: "silent", "error", "warn" (default), "info" # Default Admin User # Set a custom password for the default admin user created on first startup # If not set, a random 16-character password will be generated and written to authgate-credentials.txt # DEFAULT_ADMIN_PASSWORD=your-secure-admin-password # Authentication Mode # Options: local, http_api # Default: local AUTH_MODE=local # HTTP API Authentication (when AUTH_MODE=http_api) HTTP_API_URL=https://auth.example.com/api/verify HTTP_API_TIMEOUT=10s HTTP_API_INSECURE_SKIP_VERIFY=false # HTTP API Retry Configuration # Automatic retry with exponential backoff for failed requests HTTP_API_MAX_RETRIES=3 # Maximum retry attempts (default: 3, set 0 to disable) HTTP_API_RETRY_DELAY=1s # Initial retry delay (default: 1s) HTTP_API_MAX_RETRY_DELAY=10s # Maximum retry delay (default: 10s) # JWT Token Expiration JWT_EXPIRATION=10h # Access token lifetime (default: 10h) JWT_EXPIRATION_JITTER=30m # Max random jitter on access token expiry (default: 30m) # Must be less than JWT_EXPIRATION. Prevents refresh thundering herd. # Example: JWT_EXPIRATION=8h + JWT_EXPIRATION_JITTER=30m โ†’ lifetime [8h, 8h30m) # Refresh Token Configuration REFRESH_TOKEN_EXPIRATION=720h # Refresh token lifetime (default: 30 days) ENABLE_REFRESH_TOKENS=true # Feature flag to enable/disable refresh tokens ENABLE_TOKEN_ROTATION=false # Enable rotation mode (default: fixed mode) # Client Credentials Flow (RFC 6749 ยง4.4) # CLIENT_CREDENTIALS_TOKEN_EXPIRATION=1h # Access token lifetime for client_credentials grant (default: 1h) # # Keep short โ€” no refresh token means no rotation mechanism # OAuth Configuration (optional - for third-party login) # GitHub OAuth GITHUB_OAUTH_ENABLED=false GITHUB_CLIENT_ID=your_github_client_id GITHUB_CLIENT_SECRET=your_github_client_secret GITHUB_REDIRECT_URL=http://localhost:8080/auth/callback/github GITHUB_SCOPES=user:email # Gitea OAuth GITEA_OAUTH_ENABLED=false GITEA_URL=https://gitea.example.com GITEA_CLIENT_ID=your_gitea_client_id GITEA_CLIENT_SECRET=your_gitea_client_secret GITEA_REDIRECT_URL=http://localhost:8080/auth/callback/gitea GITEA_SCOPES=read:user # Microsoft Entra ID (Azure AD) OAuth MICROSOFT_OAUTH_ENABLED=false MICROSOFT_TENANT_ID=common MICROSOFT_CLIENT_ID= MICROSOFT_CLIENT_SECRET= MICROSOFT_REDIRECT_URL=http://localhost:8080/auth/callback/microsoft MICROSOFT_SCOPES=openid,profile,email,User.Read # OAuth Settings OAUTH_AUTO_REGISTER=true # Allow OAuth to auto-create accounts (default: true) OAUTH_TIMEOUT=15s # HTTP client timeout for OAuth requests (default: 15s) OAUTH_INSECURE_SKIP_VERIFY=false # Skip TLS verification for OAuth (dev/testing only, default: false) # Authorization Code Flow (RFC 6749 + RFC 7636) AUTH_CODE_EXPIRATION=10m # Authorization code lifetime (default: 10 min) PKCE_REQUIRED=false # Require PKCE for all clients, including confidential (default: false) CONSENT_REMEMBER=true # Skip consent page if user already approved same scopes (default: true) ``` -------------------------------- ### UptimeRobot Alert Configuration Source: https://github.com/go-authgate/authgate/blob/main/docs/MONITORING.md Example configuration for setting up a health check alert in UptimeRobot for the AuthGate service. ```text Alert Name: AuthGate Health Check Monitor Type: HTTP(s) URL: https://auth.yourdomain.com/health Interval: 5 minutes Alert Contacts: email, slack, pagerduty ``` -------------------------------- ### GET /oauth/userinfo Source: https://context7.com/go-authgate/authgate/llms.txt Retrieve user profile claims for the authenticated user using a valid access token. ```APIDOC ## GET /oauth/userinfo ### Description Retrieve user profile claims for the authenticated user using a valid access token. ### Method GET ### Endpoint https://auth.example.com/oauth/userinfo ``` -------------------------------- ### Configure AuthGate Environment Variables Source: https://github.com/go-authgate/authgate/blob/main/docs/CONFIGURATION.md Settings for dynamic client registration, user caching, and audit logging parameters. ```bash ENABLE_DYNAMIC_CLIENT_REGISTRATION=false # Enable POST /oauth/register (default: false) DYNAMIC_CLIENT_REGISTRATION_TOKEN= # Optional Bearer token for protected registration DYNAMIC_CLIENT_REGISTRATION_RATE_LIMIT=5 # Rate limit (default: 5 req/min) # User Cache # Caches GetUserByID results โ€” called on every protected request (RequireAuth + RequireAdmin) # USER_CACHE_TYPE=memory # Options: memory, redis, redis-aside (default: memory) # USER_CACHE_TTL=5m # How long to cache a user object (default: 5m) # USER_CACHE_CLIENT_TTL=30s # Client-side TTL for redis-aside mode only (default: 30s) # USER_CACHE_SIZE_PER_CONN=32 # Client-side cache size per connection in MB for redis-aside (default: 32MB) # Audit Logging # Comprehensive audit logging for security and compliance ENABLE_AUDIT_LOGGING=true # Enable audit logging (default: true) AUDIT_LOG_RETENTION=2160h # Retention period: 90 days (default: 90 days = 2160h) AUDIT_LOG_BUFFER_SIZE=1000 # Async buffer size (default: 1000) AUDIT_LOG_CLEANUP_INTERVAL=24h # Cleanup frequency (default: 24h) ``` -------------------------------- ### GET /.well-known/jwks.json Source: https://github.com/go-authgate/authgate/blob/main/docs/JWT_VERIFICATION.md Retrieves the JSON Web Key Set (JWKS) used for verifying JWT signatures. ```APIDOC ## GET /.well-known/jwks.json ### Description Retrieves the public keys used to verify JWT signatures. Resource servers should cache this response for up to 1 hour. ### Method GET ### Endpoint /.well-known/jwks.json ### Response #### Success Response (200) - **keys** (array) - List of public keys #### Response Example { "keys": [ { "kty": "RSA", "use": "sig", "kid": "abc123...", "alg": "RS256", "n": "0vx7agoebGc...", "e": "AQAB" } ] } ``` -------------------------------- ### GET /oauth/tokeninfo Source: https://github.com/go-authgate/authgate/blob/main/docs/CLIENT_CREDENTIALS_FLOW.md Verifies an access token and returns its metadata. Requires the token to be passed in the Authorization header. ```APIDOC ## GET /oauth/tokeninfo ### Description Verifies an access token and returns associated metadata. The token must be provided in the Authorization: Bearer header. ### Method GET ### Endpoint /oauth/tokeninfo ### Request Example GET /oauth/tokeninfo HTTP/1.1 Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ### Response #### Success Response (200) - **active** (boolean) - Token validity status - **user_id** (string) - Identifier for the client - **client_id** (string) - The client ID - **scope** (string) - Granted scopes - **exp** (integer) - Expiration timestamp - **iss** (string) - Issuer URL - **subject_type** (string) - Type of subject (e.g., 'client') #### Response Example { "active": true, "user_id": "client:a1b2c3d4-...", "client_id": "a1b2c3d4-...", "scope": "read", "exp": 1736899200, "iss": "https://auth.example.com", "subject_type": "client" } ``` -------------------------------- ### Configure Token Cache with Redis-Aside Source: https://github.com/go-authgate/authgate/blob/main/docs/CONFIGURATION.md Enable token cache with redis-aside for real-time invalidation across all pods. Requires Redis >= 7.0. ```bash # Or redis-aside for real-time invalidation across all pods (requires Redis >= 7.0) TOKEN_CACHE_ENABLED=true TOKEN_CACHE_TYPE=redis-aside REDIS_ADDR=redis-service:6379 TOKEN_CACHE_CLIENT_TTL=1h TOKEN_CACHE_SIZE_PER_CONN=32 ``` -------------------------------- ### AuthGate Server Configuration Source: https://context7.com/go-authgate/authgate/llms.txt Configure AuthGate deployment using environment variables for customization. ```bash # .env configuration file ``` -------------------------------- ### GET /admin/audit/export Source: https://github.com/go-authgate/authgate/blob/main/docs/MONITORING.md Exports filtered audit logs as a CSV file for external analysis or compliance reporting. ```APIDOC ## GET /admin/audit/export ### Description Exports audit logs as a CSV file based on provided filters. ### Method GET ### Endpoint /admin/audit/export ### Parameters #### Query Parameters - **severity** (string) - Optional - Filter by severity level (e.g., CRITICAL) ### Request Example curl "http://localhost:8080/admin/audit/export?severity=CRITICAL" -H "Cookie: session=..." -o critical-events.csv ```