Thanks to visit codestin.com
Credit goes to github.com

Skip to content

WanderingHumanid/auth-server

Β 
Β 


Auth Server β€” Production-Ready Authentication Microservice in Go



A complete, enterprise-grade auth backend β€” JWT, OAuth 2.0 Provider, MFA, RBAC, Social Login β€”
in a single deployable Go binary.


Live API Docs NPM SDK Release License


Go Gin PostgreSQL Redis Docker JWT TypeScript


Β  Β 



Explore the API β†’ Β Β Β·Β Β  Report Bug Β Β Β·Β Β  Request Feature Β Β Β·Β Β  Contributing




πŸ’‘ Why Auth Server?

Building authentication from scratch is tedious, error-prone, and takes weeks away from your actual product. Auth Server gives you a battle-tested, self-hosted auth backend that deploys in under 5 minutes.

Ship your product, not your auth layer.

For Developers

  • Drop-in backend for any frontend stack
  • Official TypeScript SDK with React & Next.js bindings
  • Interactive Swagger docs β€” test every endpoint live
  • Clean Architecture β€” easy to fork, extend, or contribute to
  • Zero vendor lock-in β€” MIT licensed, self-hosted

For Teams & Startups

  • Self-hosted β€” your data never leaves your infrastructure
  • Full OAuth 2.0 Provider β€” let third-party apps auth against you
  • RBAC, audit logs, and account lockout built-in
  • Docker-ready with one-command deployment
  • Built-in keep-alive pinger for free-tier hosting



🧬 Feature Matrix

πŸ” Core Authentication πŸ›‘ Security & Compliance

β€’ JWT access & refresh token rotation
β€’ Email/password registration & login
β€’ Email verification & password reset
β€’ Social login β€” Google & GitHub
β€’ Multi-Factor Auth (TOTP)
β€’ Session management & multi-device logout

β€’ BCrypt password hashing
β€’ Redis-backed rate limiting
β€’ Token blacklist & revocation
β€’ CSP, CORS & security headers
β€’ Account lockout on failed attempts
β€’ Audit trail logging

🌐 OAuth 2.0 Provider 🧩 Developer Experience

β€’ Authorization Code flow (PKCE-ready)
β€’ Client registration & management
β€’ User consent screen
β€’ Per-client provider configuration
β€’ Token exchange & /userinfo endpoint
β€’ Client secret rotation & deletion

β€’ TypeScript SDK on npm
β€’ React hooks β€” AuthProvider + useAuth
β€’ Next.js SSR adapter
β€’ Admin SDK for user management
β€’ Interactive Swagger docs
β€’ Docker Compose one-command setup


πŸ—Ί Roadmap

Status Feature Description
πŸ”œ Webhooks Notify external systems on auth events (login, register, lock)
πŸ”œ SAML / SSO Enterprise single sign-on for corporate identity providers
πŸ”œ Passkeys / WebAuthn Passwordless authentication with biometrics
πŸ”œ Flutter SDK Mobile-first auth client for iOS & Android
πŸ’­ Go SDK Server-to-server auth client for microservice architectures
πŸ’­ Magic Links Passwordless email-based login flow

Have an idea? Open a discussion β†’




πŸ› Architecture

Auth Server follows Clean Architecture with strict separation of concerns:

auth-server/
β”œβ”€β”€ cmd/server/main.go              # Entry point β€” Gin setup, GORM migration, graceful shutdown
β”œβ”€β”€ internal/
β”‚   β”œβ”€β”€ config/                     # Configuration loading, DB & Redis initialization
β”‚   β”œβ”€β”€ routes/                     # Route definitions & middleware registration
β”‚   β”œβ”€β”€ handler/                    # HTTP handlers β€” request parsing & response formatting
β”‚   β”œβ”€β”€ service/                    # Business logic β€” auth flows, OAuth, MFA, email
β”‚   β”œβ”€β”€ repository/                 # Data access layer β€” isolated GORM queries
β”‚   β”œβ”€β”€ models/                     # GORM models β€” User, RefreshToken, OAuthClient, etc.
β”‚   β”œβ”€β”€ middleware/                 # Auth, CORS, CSP, rate limiting, recovery
β”‚   β”œβ”€β”€ dto/                        # Request/response data transfer objects
β”‚   └── utils/                      # Helpers β€” validation, error types, JWT claims
β”œβ”€β”€ clients/ts/                     # Official TypeScript SDK (published to npm)
β”œβ”€β”€ templates/                      # Email templates (HTML)
β”œβ”€β”€ docs/                           # Swagger UI & generated API spec
└── docker-compose.yml              # PostgreSQL + Redis orchestration



πŸ›  Tech Stack

Layer Technology Purpose
Language Go 1.25+ High-performance compiled backend
Framework Gin Gonic Fast HTTP router with middleware pipeline
Database PostgreSQL 15+ Relational data store via GORM ORM
Cache Redis 7+ Rate limiting, token blacklist, sessions
Auth JWT + OAuth 2.0 + TOTP Industry-standard protocols
Hashing BCrypt Secure password storage
Email SMTP (Gmail, SendGrid, etc.) Transactional email delivery
Docs Swagger / OpenAPI 3.0 Interactive API documentation
SDK TypeScript React, Next.js, & Node.js bindings
Deploy Docker & Docker Compose Containerized deployment



πŸš€ Quick Start

Prerequisites

  • Go 1.25+ Β Β·Β  Docker & Docker Compose Β Β·Β  PostgreSQL 15+ Β Β·Β  Redis 7+

Option A β€” Docker (Recommended)

git clone https://github.com/roshankumar0036singh/auth-server.git
cd auth-server
cp .env.example .env        # ← configure your secrets
docker compose up --build -d

Server runs at http://localhost:8080 Β Β·Β  Swagger UI at /swagger/

Option B β€” Local Development

git clone https://github.com/roshankumar0036singh/auth-server.git
cd auth-server

# Install dependencies
go mod download

# Configure environment
cp .env.example .env

# Start PostgreSQL & Redis
docker compose up -d db redis

# Run the server
go run cmd/server/main.go

Option C β€” Makefile

make run          # Start the server
make test         # Run all tests
make swagger      # Regenerate API docs
make build-prod   # Static production binary



πŸ“‘ API Overview

Full interactive docs β†’

Authentication

Method Endpoint Description
POST /api/auth/register Create a new account
POST /api/auth/login Authenticate with credentials
POST /api/auth/login/mfa Complete MFA challenge
POST /api/auth/refresh Refresh access token
POST /api/auth/logout Revoke current session
POST /api/auth/logout-all Revoke all sessions

User Management

Method Endpoint Description
GET /api/auth/me Get current user profile
PUT /api/auth/profile Update profile
POST /api/auth/password Change password
DELETE /api/auth/me Delete account
GET /api/auth/sessions List active sessions
DELETE /api/auth/sessions/:id Revoke specific session
GET /api/auth/audit-logs View audit trail

Email & Verification

Method Endpoint Description
GET /api/auth/verify-email Verify email address
POST /api/auth/resend-verification Resend verification email
POST /api/auth/forgot-password Request password reset
POST /api/auth/reset-password Reset password with token

MFA (Multi-Factor Authentication)

Method Endpoint Description
POST /api/auth/mfa/enable Generate TOTP secret
POST /api/auth/mfa/verify Verify and activate MFA
POST /api/auth/mfa/disable Disable MFA

Social Login

Method Endpoint Description
GET /api/auth/google/login Initiate Google OAuth
GET /api/auth/google/callback Google OAuth callback
GET /api/auth/github/login Initiate GitHub OAuth
GET /api/auth/github/callback GitHub OAuth callback

OAuth 2.0 Provider

Method Endpoint Description
GET /oauth/authorize Authorization endpoint
POST /oauth/token Token exchange
GET /oauth/userinfo Get authorized user info
POST /api/auth/oauth/clients Register OAuth client
GET /api/auth/oauth/clients List your OAuth clients
DELETE /api/auth/oauth/clients/:id Delete OAuth client

Admin (Requires admin Role)

Method Endpoint Description
GET /api/admin/users List all users (paginated)
POST /api/admin/users/:id/lock Lock user account
POST /api/admin/users/:id/unlock Unlock user account
DELETE /api/admin/users/:id Delete user account



πŸ“¦ TypeScript SDK

The official SDK is published on npm as @authserver/client.

npm install @authserver/client

Vanilla TypeScript

import { AuthClient } from '@authserver/client';

const auth = new AuthClient({
  serverUrl: 'https://your-auth-server.com',
  clientId: 'your-client-id',
  storage: 'localStorage',
  keepAlive: true,  // prevents server sleep on free-tier hosting
});

// Register & login
await auth.register('[email protected]', 'securePassword123', 'John');
const session = await auth.login('[email protected]', 'securePassword123');

// Automatic token refresh β€” just call methods
const user = await auth.getUser();

// Listen for auth events
auth.on('logout', () => console.log('User signed out'));

// Cleanup when done
auth.destroy();

React

import { AuthProvider, useAuth } from '@authserver/client/react';

function App() {
  return (
    <AuthProvider serverUrl="https://your-auth-server.com" clientId="your-client-id">
      <Dashboard />
    </AuthProvider>
  );
}

function Dashboard() {
  const { user, login, logout, isAuthenticated } = useAuth();

  if (!isAuthenticated) return <button onClick={() => login('[email protected]', 'pw')}>Login</button>;
  return <p>Welcome, {user?.name}! <button onClick={logout}>Logout</button></p>;
}

Next.js (SSR)

import { createNextAuthClient } from '@authserver/client/nextjs';

export const { withAuth, getSession, handlers } = createNextAuthClient({
  serverUrl: 'https://your-auth-server.com',
  clientId: 'your-client-id',
});

Admin SDK

import { AdminClient } from '@authserver/client/admin';

const admin = new AdminClient({
  serverUrl: 'https://your-auth-server.com',
  adminToken: 'your-admin-jwt',
});

const users = await admin.listUsers();
await admin.lockUser('user-uuid');

Full SDK documentation β†’




βš™ Environment Configuration

Copy .env.example to .env and configure:

Variable Required Description
APP_ENV Yes development or production
DATABASE_URL Yes PostgreSQL connection string
REDIS_URL Yes Redis connection string
JWT_SECRET Yes Access token signing key
JWT_REFRESH_SECRET Yes Refresh token signing key
SMTP_HOST Yes Email SMTP server
SMTP_USER / SMTP_PASSWORD Yes SMTP credentials
GOOGLE_CLIENT_ID / SECRET No Google OAuth (optional)
GITHUB_CLIENT_ID / SECRET No GitHub OAuth (optional)
PING_URL No Self-ping URL to prevent free-tier sleep
ENCRYPTION_KEY Yes 32-byte key for sensitive data encryption
BCRYPT_ROUNDS No Password hashing cost (default: 12)



πŸ§ͺ Testing

# Run all tests
go test ./...

# Run tests with verbose output
go test ./internal/service -v

# Run a specific test
go test ./internal/service -run TestTokenService_GenerateAccessToken -v

# Generate HTML coverage report
go test ./... -coverprofile=coverage.out && go tool cover -html=coverage.out



🐳 Deployment

Docker Compose (Full Stack)

docker compose up --build -d

This starts:

  • Auth Server on port 8080
  • PostgreSQL on port 5432
  • Redis on port 6379

Production Build

# Static binary (no CGO dependencies)
make build-prod

# Or manually:
CGO_ENABLED=0 GOOS=linux go build -o auth-server cmd/server/main.go

Cloud Deployment

Platform Guide
Render Connect repo β†’ set env vars β†’ auto-deploy
Railway One-click Go template β†’ configure .env
Fly.io fly launch β†’ fly deploy
AWS / GCP / Azure Docker image or binary deployment

Tip: Set PING_URL to your public URL's /health endpoint to prevent free-tier platforms from putting your server to sleep. Auth Server includes a built-in self-pinger that hits this URL every 14 minutes.




🀝 Contributing

We welcome contributions of all sizes β€” from typo fixes to new features.

# Fork β†’ Clone β†’ Branch
git checkout -b feature/your-feature

# Make changes β†’ Test
go test ./...

# Commit (we use Conventional Commits)
git commit -m "feat: add amazing feature"

# Push β†’ Open PR
git push origin feature/your-feature

Read the full Contributing Guide β†’ Β Β·Β  Code of Conduct β†’

Ways to Contribute

  • Bug reports β€” Open an issue
  • Feature requests β€” Start a discussion
  • Documentation β€” Improve guides, add examples
  • Tests β€” Increase coverage, add edge cases
  • Integrations β€” Build SDKs for other languages



πŸ“„ License

Distributed under the MIT License. See LICENSE for details.


Author

Roshan Kumar Singh

GitHub


If Auth Server helped you, consider giving it a ⭐


About

Auth Server is a robust, production-ready authentication microservice built with Go and Gin. It provides a full OAuth 2.0 Provider implementation, MFA, and RBAC out of the box.

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • Go 71.0%
  • TypeScript 16.5%
  • JavaScript 6.0%
  • HTML 5.1%
  • CSS 0.8%
  • Makefile 0.3%
  • Dockerfile 0.3%