A secure Go API gateway with JWT authentication and role-based access control (RBAC).
- JWT Authentication: Configurable secret keys, issuer, and audience validation
- Token Validation: Expiration, issuer, and audience checks
- RBAC Support: Role-based access control for different endpoints
- Middleware: Reusable authentication and authorization middleware
- Helper Functions: Easy extraction of claims from JWT tokens
- Configuration: Environment-based configuration management
- API Documentation: Interactive Swagger UI with comprehensive endpoint documentation
api-gateway/
├── auth/
│ ├── jwt.go # JWT token generation and validation
│ └── middleware.go # Authentication and RBAC middleware
├── config/
│ └── config.go # Configuration management
├── docs/
│ ├── docs.go # Swagger documentation
│ └── swagger.json # OpenAPI specification
├── handlers/
│ ├── auth.go # Authentication endpoints
│ ├── protected.go # Protected endpoints with role examples
│ └── swagger.go # Swagger documentation handler
├── main.go # Main application entry point
├── test_api.sh # API testing script
├── go.mod # Go module dependencies
└── README.md # This file
-
Using Docker Compose (easiest):
make compose-up
-
Using Docker directly:
make docker-run
-
Using Makefile (development):
make dev
-
Install dependencies:
make deps
-
Set environment variables (optional):
export JWT_SECRET="your-secret-key-here" export JWT_ISSUER="api-gateway" export JWT_AUDIENCE="api-users" export JWT_EXPIRY_HOURS="24" export PORT="8080"
-
Run the application:
make run
Run make help
to see all available commands:
# Development Commands
make dev # Start development environment with hot reload
make dev-local # Start local development with hot reload (requires air)
make watch # Alias for dev command
make watch-files # Watch for file changes and show notifications
make dev-status # Show development environment status
# Docker Commands
make compose-up # Start with Docker Compose
make compose-up-dev # Start development services with hot reload
make compose-up-prod # Start production services with nginx
make docker-run # Build and run with Docker
make docker-build # Build Docker image
# Utility Commands
make build # Build the Go application
make run # Build and run locally
make test-api # Test API endpoints
make status # Show service status
make health # Check API health
make install-tools # Install development tools
POST /login
- User loginGET /health
- Health checkGET /swagger/
- Interactive Swagger UI documentationGET /docs
- Redirect to Swagger UIGET /swagger/doc.json
- OpenAPI specification (JSON)
GET /api/profile
- Get user profilePOST /api/refresh
- Refresh JWT tokenGET /api/user
- User endpoint (any authenticated user)GET /api/moderator
- Moderator only (requires moderator role)GET /api/admin
- Admin only (requires admin role)GET /api/mixed
- Admin or Moderator (requires admin or moderator role)
curl -X POST http://localhost:8080/login \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "admin123"}'
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
http://localhost:8080/api/profile
Username | Password | Roles |
---|---|---|
admin | admin123 | admin, user |
moderator | mod123 | moderator, user |
user | user123 | user |
The JWT configuration can be set via environment variables:
JWT_SECRET
: Secret key for signing tokens (default: "default-secret-key")JWT_ISSUER
: Token issuer (default: "api-gateway")JWT_AUDIENCE
: Token audience (default: "api-users")JWT_EXPIRY_HOURS
: Token expiry in hours (default: 24)PORT
: Server port (default: "8080")
// Apply authentication to all routes
router.Use(auth.AuthMiddleware(jwtManager))
// Require specific roles
router.HandleFunc("/admin", handler.AdminOnly).Methods("GET").
Middleware(auth.RBACMiddleware("admin"))
// Require multiple roles (OR logic)
router.HandleFunc("/moderator", handler.ModeratorOnly).Methods("GET").
Middleware(auth.RBACMiddleware("admin", "moderator"))
// Get user claims
claims, ok := auth.GetClaimsFromContext(r.Context())
if ok {
userID := claims.UserID
roles := claims.Roles
}
// Get specific user info
userID, ok := auth.GetUserIDFromContext(r.Context())
roles, ok := auth.GetUserRolesFromContext(r.Context())
// Check specific role
isAdmin := auth.HasRole(r.Context(), "admin")
- Token Validation: Comprehensive JWT validation including expiration, issuer, and audience
- Role-Based Access: Fine-grained access control based on user roles
- Context Integration: Seamless integration with Go's context package
- Error Handling: Proper HTTP status codes and error messages
- CORS Support: Built-in CORS middleware for web applications
The API includes comprehensive Swagger documentation accessible at:
- Swagger UI:
http://localhost:8080/swagger/
- Interactive documentation interface - OpenAPI JSON:
http://localhost:8080/swagger/doc.json
- Machine-readable API specification - Quick Access:
http://localhost:8080/docs
- Redirects to Swagger UI
The documentation includes:
- Complete endpoint descriptions
- Request/response schemas
- Authentication requirements
- Role-based access control details
- Interactive testing capabilities
- Get a JWT Token: Use the
/login
endpoint with valid credentials - Authorize in Swagger: Click "Authorize" button and enter
Bearer <your-token>
- Test Protected Endpoints: All protected endpoints will now work with your token
Available Test Credentials:
- Admin:
admin
/admin123
- User:
user
/user123
- Moderator:
moderator
/mod123
📖 Detailed Guide: See SWAGGER_AUTH_GUIDE.md for step-by-step instructions
The project includes a complete Docker setup for easy deployment and development:
Dockerfile
- Multi-stage build for production-ready imageDockerfile.dev
- Development image with hot reload supportdocker-compose.yml
- Service orchestration with optional nginxdocker-compose.override.yml
- Development overrides with hot reloaddocker-compose.dev.yml
- Alternative development configuration.dockerignore
- Excludes unnecessary files from Docker contextnginx.conf
- Reverse proxy configuration for production.air.toml
- Air configuration for hot reload
- Multi-stage build for optimized image size
- Non-root user for security
- Health checks for container monitoring
- Environment variable configuration
- Nginx reverse proxy for production deployments
- Hot reload for development with file watching
- Volume mounting for live code updates
- File watching with automatic rebuilds
- Hot reload using Air (Go hot reload tool)
- Volume mounting for instant code changes
- Development tools auto-installation
- Multiple development modes (Docker vs local)
-
Start development environment:
make dev
-
Make code changes - The server will automatically rebuild and restart
-
View logs to see rebuild notifications:
make compose-logs-dev
-
Check development status:
make dev-status
-
Stop development environment:
make compose-down-dev
The development environment automatically detects changes to:
.go
files (Go source code).html
files (templates).toml
files (configuration).json
files (configuration)
Changes trigger:
- Automatic rebuild of the application
- Container restart with new code
- Log notifications of the rebuild process
-
With Nginx (recommended for production):
make compose-up-prod
-
Environment Configuration:
# Create .env file echo "JWT_SECRET=your-production-secret-key" > .env echo "JWT_ISSUER=your-domain.com" >> .env echo "JWT_AUDIENCE=your-api-users" >> .env # Start with environment file docker-compose --env-file .env up -d
github.com/golang-jwt/jwt/v5
- JWT token handlinggithub.com/gorilla/mux
- HTTP routergithub.com/joho/godotenv
- Environment variable loadinggithub.com/swaggo/swag
- Swagger documentation generationgithub.com/swaggo/http-swagger
- Swagger UI servinggithub.com/swaggo/files
- Static file serving for Swagger
MIT License