README
¶
Auth Chassis - Reusable Authentication Service
A comprehensive, production-ready authentication service built with Go and gRPC. This chassis provides a complete authentication solution that can be easily integrated into any application.
Features
Authentication Methods
- Email/Password Authentication: Traditional email and password-based authentication with secure password hashing (bcrypt)
- Passwordless Authentication: Magic link authentication via email
- OAuth 2.0: Support for Google, GitHub, Facebook, Apple, Microsoft, and Discord OAuth providers
- Two-Factor Authentication (2FA): TOTP-based 2FA with QR code generation and backup codes
Security Features
- JWT-based access and refresh tokens
- Secure password hashing with bcrypt
- Password strength validation
- Email verification
- Session management
- Token refresh mechanism
- 2FA with backup codes
Additional Features
- User profile management
- Password reset flow
- Session tracking and revocation
- PostgreSQL database with GORM
- UUID-based primary keys (generated by PostgreSQL)
- Customizable email templates (text-based, easy to modify)
- SendGrid integration for production email sending
- Comprehensive gRPC API
Architecture
auth/
├── api/proto/auth/v1/ # gRPC protocol definitions
├── cmd/server/ # Application entry point
├── internal/
│ ├── config/ # Configuration management
│ ├── database/ # Database initialization
│ ├── domain/ # Domain models
│ ├── repository/ # Data access layer
│ └── service/ # Business logic
├── .env.example # Environment variables template
├── config.yaml.example # YAML configuration template
├── Makefile # Build and development commands
└── README.md # This file
Prerequisites
- Go 1.25.3 or higher
- PostgreSQL 12 or higher
- Protocol Buffers compiler (protoc)
Quick Start
1. Clone and Setup
# Clone the repository
cd auth
# Copy environment variables
cp .env.example .env
# Edit .env with your configuration
# IMPORTANT: Change the JWT secrets to secure random strings!
vim .env
2. Setup PostgreSQL
# Create database
createdb auth_db
# Or using psql
psql -U postgres
CREATE DATABASE auth_db;
3. Configure Environment Variables
Edit .env file and set at minimum:
AUTH_JWT_ACCESS_TOKEN_SECRET: A secure random string for access tokensAUTH_JWT_REFRESH_TOKEN_SECRET: A secure random string for refresh tokensAUTH_DATABASE_*: Your PostgreSQL connection details
Generate secure secrets:
# Generate random secrets (on macOS/Linux)
openssl rand -base64 32
4. Install Dependencies
# Install Go dependencies
go mod download
# Install protobuf tools (if not already installed)
make install-tools
5. Run the Service
# Build and run
make build
./bin/auth-server
# Or run directly
make run
The service will:
- Connect to PostgreSQL
- Run database migrations automatically
- Start the gRPC server on
:8080
Configuration
The service can be configured using:
- Environment variables (prefixed with
AUTH_) - YAML configuration file (
config.yaml) - Default values
Environment variables take precedence over YAML configuration.
Required Configuration
- JWT Secrets: Must be set via environment variables
AUTH_JWT_ACCESS_TOKEN_SECRETAUTH_JWT_REFRESH_TOKEN_SECRET
Database Configuration
database:
host: localhost
port: 5432
user: postgres
password: postgres
dbname: auth_db
sslmode: disable
Email Configuration
For development, you can leave email settings empty. Emails will be logged to console.
Option 1: SendGrid (Recommended for Production)
email:
provider: sendgrid
api_key: your-sendgrid-api-key
from_email: noreply@yourapp.com
from_name: Your App
Or via environment variables:
AUTH_EMAIL_PROVIDER=sendgrid
AUTH_EMAIL_API_KEY=SG.your-api-key-here
AUTH_EMAIL_FROM_EMAIL=noreply@yourapp.com
AUTH_EMAIL_FROM_NAME=Your App
SendGrid Setup:
- Sign up at SendGrid
- Verify your sender email/domain
- Create an API key (Settings → API Keys)
- Add the API key to your config
Option 2: SMTP (For Development)
email:
provider: smtp
smtp_host: smtp.gmail.com
smtp_port: 587
smtp_user: your-email@gmail.com
smtp_pass: your-app-password
from_email: noreply@yourapp.com
from_name: Your App
OAuth Configuration
To enable OAuth providers, configure their client credentials:
oauth:
google:
client_id: your-google-client-id
client_secret: your-google-client-secret
redirect_url: http://localhost:8080/auth/google/callback
gRPC API
The service exposes the following gRPC methods:
Authentication
Register: Register a new userLogin: Login with email/passwordRefreshToken: Refresh access tokenLogout: Logout and revoke session
Password Management
ChangePassword: Change user passwordForgotPassword: Request password resetResetPassword: Reset password with token
Two-Factor Authentication
Enable2FA: Enable 2FA for userVerify2FA: Verify 2FA codeDisable2FA: Disable 2FAGenerate2FABackupCodes: Generate new backup codes
Passwordless Authentication
SendPasswordlessEmail: Send magic linkVerifyPasswordlessToken: Verify magic link
OAuth
GetOAuthURL: Get OAuth authorization URLOAuthCallback: Handle OAuth callbackLinkOAuthAccount: Link OAuth account to userUnlinkOAuthAccount: Unlink OAuth account
Token & Session Management
ValidateToken: Validate access tokenRevokeToken: Revoke tokenGetActiveSessions: Get user's active sessionsRevokeSession: Revoke specific session
User Management
GetUserProfile: Get user profileUpdateUserProfile: Update user profileVerifyEmail: Verify email addressResendVerificationEmail: Resend verification email
Testing with grpcurl
# Install grpcurl
brew install grpcurl # macOS
# or
go install github.com/fullstorydev/grpcurl/cmd/grpcurl@latest
# List services
grpcurl -plaintext localhost:8080 list
# List methods
grpcurl -plaintext localhost:8080 list auth.v1.AuthService
# Register a new user
grpcurl -plaintext -d '{
"email": "user@example.com",
"password": "SecurePass123",
"first_name": "John",
"last_name": "Doe"
}' localhost:8080 auth.v1.AuthService/Register
# Login
grpcurl -plaintext -d '{
"email": "user@example.com",
"password": "SecurePass123"
}' localhost:8080 auth.v1.AuthService/Login
Database Schema
The service uses the following tables:
users: User accountssessions: User sessionsotps: One-time passwords/tokensoauth_accounts: OAuth account linksbackup_codes: 2FA backup codes
All tables use UUID as primary keys, generated by PostgreSQL using gen_random_uuid().
Development
Regenerate Protocol Buffers
make proto
Run Tests
make test
Build
make build
Clean
make clean
Deployment
Docker
Create a Dockerfile:
FROM golang:1.25-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o auth-server cmd/server/main.go
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/auth-server .
EXPOSE 8080
CMD ["./auth-server"]
Build and run:
docker build -t auth-service .
docker run -p 8080:8080 --env-file .env auth-service
Environment Variables for Production
Ensure these are set in production:
- Use strong, unique JWT secrets
- Enable SSL for database (
sslmode=require) - Configure proper email service
- Set up OAuth callbacks with production URLs
- Use connection pooling settings appropriate for your load
Integration Guide
To integrate this auth service into your application:
- Client-side: Use any gRPC client library
- Include access token in gRPC metadata for authenticated requests:
Authorization: Bearer <access_token> - Handle token refresh when access token expires
- Validate tokens using the
ValidateTokenendpoint
Security Considerations
- Always use HTTPS in production
- Store JWT secrets securely (use environment variables or secret management)
- Rotate JWT secrets periodically
- Implement rate limiting on authentication endpoints
- Monitor for suspicious authentication patterns
- Keep dependencies up to date
- Use strong password requirements
- Enable 2FA for sensitive accounts
License
This is a reusable chassis for building authentication services.
Support
For issues or questions, please create an issue in the repository.