Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Auth Microservice in Go with gRPC + HTTP (JWT Access/Refresh)

A production-ready, reusable authentication microservice built with Go 1.23+, gRPC, and JWT. Perfect for microservices architectures, e-commerce platforms, and portfolio projects.

Features

  • gRPC API - High-performance binary protocol for service-to-service communication
  • HTTP/JSON Gateway - REST-like interface via grpc-gateway for easy testing (Postman/curl)
  • JWT Authentication - Access tokens (15 min) + Refresh tokens (7 days) with automatic rotation
  • Token Blacklist - Redis-based refresh token revocation
  • Security - bcrypt password hashing, JWT validation via interceptors, rate limiting
  • Flexible Database - SQLite for development, PostgreSQL for production (GORM)
  • Structured Logging - zerolog for JSON-structured logging
  • Graceful Shutdown - Proper cleanup on SIGTERM/SIGINT
  • Docker Support - Containerized deployment with docker-compose

Requirements

  • Go 1.23 or higher
  • protoc (Protocol Buffer compiler)
  • Docker & Docker Compose (optional)
  • Redis (optional, for token blacklist)

Installation

  1. Clone the repository and navigate to the project:
cd auth-service
  1. Install Go dependencies:
go mod tidy
  1. Copy environment file:
cp .env.example .env
  1. Generate protobuf code:
# Install protoc plugins first
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

# Generate Go code from proto
protoc --proto_path=proto \
  --go_out=pb \
  --go_opt=paths=source_relative \
  --go-grpc_out=pb \
  --go-grpc_opt=paths=source_relative \
  proto/auth.proto

Configuration

Environment variables (see .env.example):

Variable Default Description
SERVER_GRPC_PORT 50051 gRPC server port
SERVER_HTTP_PORT 8080 HTTP gateway port
JWT_SECRET (required) Secret key for JWT signing
JWT_EXPIRY 15 Access token expiry in minutes
REFRESH_EXPIRY 7 Refresh token expiry in days
DB_DRIVER sqlite Database driver (sqlite/postgres)
DB_URL ./auth.db Database connection string
REDIS_URL redis://localhost:6379 Redis connection URL
RATE_LIMIT_QPS 10 Rate limit queries per second
RATE_LIMIT_BURST 20 Rate limit burst

Running Locally

With SQLite (Development)

go run cmd/main.go

With PostgreSQL + Redis (Production-like)

docker-compose up -d

Manual PostgreSQL + Redis

  1. Start PostgreSQL and Redis
  2. Update .env:
    DB_DRIVER=postgres
    DB_URL=postgres://user:pass@localhost:5432/auth?sslmode=disable
    REDIS_URL=redis://localhost:6379
    
  3. Run:
go run cmd/main.go

API Usage Examples

HTTP/JSON (curl/Postman)

Register

curl -X POST http://localhost:8080/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"password123"}'

Login

curl -X POST http://localhost:8080/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"password123"}'

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "refresh_token": "uuid-string-here",
  "expires_in": 900
}

Validate Token

curl -X POST http://localhost:8080/v1/auth/validate \
  -H "Content-Type: application/json" \
  -d '{"access_token":"eyJhbGciOiJIUzI1NiIs..."}'

Refresh Token

curl -X POST http://localhost:8080/v1/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{"refresh_token":"uuid-string-here"}'

Logout

curl -X POST http://localhost:8080/v1/auth/logout \
  -H "Content-Type: application/json" \
  -d '{"refresh_token":"uuid-string-here"}'

gRPC (grpcurl)

# Register
grpcurl -d '{"email":"user@example.com","password":"password123"}' \
  localhost:50051 auth.AuthService/Register

# Login
grpcurl -d '{"email":"user@example.com","password":"password123"}' \
  localhost:50051 auth.AuthService/Login

# Validate
grpcurl -d '{"access_token":"eyJ..."}' \
  -H "authorization: Bearer eyJ..." \
  localhost:50051 auth.AuthService/Validate

# Refresh
grpcurl -d '{"refresh_token":"uuid..."}' \
  localhost:50051 auth.AuthService/Refresh

# Logout
grpcurl -d '{"refresh_token":"uuid..."}' \
  localhost:50051 auth.AuthService/Logout

Security Recommendations for Production

  1. Use HTTPS/TLS - Enable TLS for both gRPC and HTTP endpoints
  2. Rotate JWT Secret - Change JWT_SECRET regularly and store in secure vault
  3. mTLS for gRPC - Implement mutual TLS for internal service communication
  4. Monitor Redis - Set up alerts for Redis memory/disk usage
  5. Rate Limiting - Adjust rate limits based on traffic patterns
  6. Input Validation - Add additional validation (email verification, password strength)
  7. Logging & Monitoring - Integrate with Prometheus/Grafana for metrics

Architecture

┌─────────────────┐      ┌─────────────────┐
│   gRPC Client  │      │  HTTP Client    │
│   (Service)    │      │ (Postman/curl)  │
└────────┬────────┘      └────────┬────────┘
         │                       │
         ▼                       ▼
┌─────────────────────────────────────────┐
│           gRPC Server (50051)           │
│  ┌─────────────────────────────────┐    │
│  │  Auth Interceptor (JWT Check)  │    │
│  └─────────────────────────────────┘    │
│                  │                       │
│  ┌──────────────────────────────────┐  │
│  │      AuthService Implementation  │  │
│  └──────────────────────────────────┘  │
└────────┬──────────────────────┬────────┘
         │                      │
         ▼                      ▼
┌─────────────────┐    ┌─────────────────┐
│  GORM (SQLite/ │    │  Redis          │
│  PostgreSQL)   │    │  (Blacklist)    │
└─────────────────┘    └─────────────────┘

Project Structure

auth-service/
├── cmd/
│   └── main.go                 # Application entry point
├── internal/
│   ├── config/
│   │   └── config.go           # Viper configuration
│   ├── middleware/
│   │   ├── auth_interceptor.go # JWT validation interceptor
│   │   └── rate_limiter.go     # Rate limiting
│   ├── models/
│   │   └── user.go             # User model
│   ├── repository/
│   │   ├── user_repo.go        # User database operations
│   │   ├── token_repo.go       # Redis token blacklist
│   │   └── noop_token_repo.go  # No-op token repo fallback
│   ├── server/
│   │   ├── grpc.go             # gRPC server setup
│   │   └── gateway.go          # HTTP gateway
│   └── service/
│       └── auth_service.go     # Business logic
├── pb/                         # Generated protobuf code
├── proto/
│   └── auth.proto              # Protocol Buffer definitions
├── .env.example
├── Dockerfile
├── docker-compose.yml
├── go.mod
└── README.md

Future Improvements

  • OAuth2 social logins (Google, GitHub, etc.)
  • Email verification
  • Two-factor authentication (TOTP)
  • Prometheus metrics + Grafana dashboards
  • OpenAPI/Swagger documentation
  • Admin endpoints for user management
  • Token refresh via cookie (HTTP-only)
  • Database migrations (Golang migrate)

License

MIT License - See LICENSE for details.

About

Reusable gRPC + HTTP authentication microservice in Go with JWT access/refresh tokens, Redis blacklist, SQLite/PostgreSQL support and rate limiting. Production-ready MVP.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages