A comprehensive Identity and Access Management (IAM) service built with Go, following clean architecture principles. This service provides user, group, and role management with a RESTful API.
- User Management: Create, read, update, delete users with password hashing
- Group Management: Organize users into groups with hierarchical permissions
- Role-based Access Control: Assign roles to users and groups
- Keycloak Integration: Full integration with Keycloak for authentication and user management
- JWT Authentication: Token-based authentication using Keycloak JWT tokens
- User Synchronization: Bidirectional sync between local database and Keycloak
- RESTful API: Complete HTTP API with proper status codes and error handling
- Database Integration: PostgreSQL with GORM ORM
- Comprehensive Testing: Unit tests with mocks using testify and mockery
- Clean Architecture: Separation of concerns with domain, repository, service, and transport layers
- Structured Logging: Uber Zap logger with configurable levels and formats
- Configuration Management: Viper-based configuration with environment variable support
- Health Checks: Built-in health check endpoints including Keycloak connectivity
- Graceful Shutdown: Proper server shutdown handling
This project follows Clean Architecture principles:
├── cmd/server/ # Application entry point
├── internal/
│ ├── domain/ # Business entities and domain logic
│ ├── repository/ # Data access layer interfaces and implementations
│ ├── service/ # Business logic layer
│ ├── transport/http/ # HTTP handlers and routing
│ ├── database/ # Database connection and migrations
│ └── config/ # Configuration management
├── pkg/
│ ├── logger/ # Logging utilities
│ └── validator/ # Request validation utilities
└── tests/
├── mocks/ # Generated mocks for testing
└── fixtures/ # Test data fixtures
- Go 1.23+
- PostgreSQL 12+
- Docker and Docker Compose (optional)
- Clone the repository:
git clone <repository-url>
cd keycloak-iam-service- Install dependencies:
go mod tidy- Set up the database:
# Using Docker Compose (recommended)
docker-compose up -d postgres
# Or set up PostgreSQL manually and create database
createdb keycloak_iam- Configure the application:
# Copy the example configuration
cp config.yaml config.local.yaml
# Edit config.local.yaml with your database settings- Run database migrations:
go run cmd/server/main.go
# Migrations run automatically on startup- Start the server:
go run cmd/server/main.goThe server will start on http://localhost:8080 by default.
The application can be configured using:
- Configuration files (YAML):
config.yaml,config.local.yaml - Environment variables: All config keys can be set as env vars with
_separators
| Key | Environment Variable | Default | Description |
|---|---|---|---|
server.host |
SERVER_HOST |
0.0.0.0 |
Server bind address |
server.port |
SERVER_PORT |
8080 |
Server port |
server.environment |
SERVER_ENVIRONMENT |
development |
Environment (development/production) |
database.host |
DATABASE_HOST |
localhost |
Database host |
database.port |
DATABASE_PORT |
5432 |
Database port |
database.user |
DATABASE_USER |
postgres |
Database username |
database.password |
DATABASE_PASSWORD |
`` | Database password |
database.dbname |
DATABASE_DBNAME |
keycloak_iam |
Database name |
keycloak.url |
KEYCLOAK_URL |
http://localhost:8080 |
Keycloak server URL |
keycloak.realm |
KEYCLOAK_REALM |
master |
Keycloak realm |
keycloak.client_id |
KEYCLOAK_CLIENT_ID |
admin-cli |
Keycloak client ID |
keycloak.client_secret |
KEYCLOAK_CLIENT_SECRET |
`` | Keycloak client secret |
keycloak.admin_user |
KEYCLOAK_ADMIN_USER |
admin |
Keycloak admin username |
keycloak.admin_pass |
KEYCLOAK_ADMIN_PASS |
admin_password |
Keycloak admin password |
logger.level |
LOGGER_LEVEL |
info |
Log level (debug/info/warn/error) |
logger.format |
LOGGER_FORMAT |
json |
Log format (json/console) |
http://localhost:8080/api/v1
GET /healthPOST /api/v1/auth/login
Content-Type: application/json
{
"username": "admin",
"password": "admin_password"
}POST /api/v1/auth/refresh
Content-Type: application/json
{
"refresh_token": "your-refresh-token"
}POST /api/v1/auth/logout
Content-Type: application/json
{
"refresh_token": "your-refresh-token"
}GET /api/v1/auth/userinfo
Authorization: Bearer your-access-tokenPOST /api/v1/auth/validate
Authorization: Bearer your-access-tokenNote: All user management endpoints require authentication (Bearer token)
POST /api/v1/users
Content-Type: application/json
{
"username": "johndoe",
"email": "john@example.com",
"first_name": "John",
"last_name": "Doe",
"password": "securepassword123"
}GET /api/v1/users/{id}PUT /api/v1/users/{id}
Content-Type: application/json
{
"first_name": "Jane",
"last_name": "Smith",
"is_active": true
}GET /api/v1/users?page=1&limit=10&search=john&is_active=trueDELETE /api/v1/users/{id}POST /api/v1/users/{id}/activate
POST /api/v1/users/{id}/deactivate
POST /api/v1/users/{id}/verify
POST /api/v1/users/{id}/change-passwordGET /api/v1/users/{id}/groups
GET /api/v1/users/{id}/roles
POST /api/v1/users/{id}/groups
POST /api/v1/users/{id}/rolesPOST /api/v1/groups
Content-Type: application/json
{
"name": "Administrators",
"description": "System administrators group"
}GET /api/v1/groups
GET /api/v1/groups/{id}
PUT /api/v1/groups/{id}
DELETE /api/v1/groups/{id}GET /api/v1/groups/{id}/users
GET /api/v1/groups/{id}/roles
POST /api/v1/groups/{id}/users
DELETE /api/v1/groups/{id}/users
POST /api/v1/groups/{id}/rolesPOST /api/v1/roles
Content-Type: application/json
{
"name": "admin",
"description": "Administrator role with full access"
}GET /api/v1/roles
GET /api/v1/roles/{id}
PUT /api/v1/roles/{id}
DELETE /api/v1/roles/{id}GET /api/v1/roles/{id}/users
GET /api/v1/roles/{id}/groups
POST /api/v1/roles/{id}/users
POST /api/v1/roles/{id}/groupsNote: All synchronization endpoints require authentication and admin privileges
POST /api/v1/sync/users/to-keycloak
Authorization: Bearer your-access-tokenPOST /api/v1/sync/users/from-keycloak
Authorization: Bearer your-access-tokenPOST /api/v1/sync/groups/to-keycloak
Authorization: Bearer your-access-tokenPOST /api/v1/sync/groups/from-keycloak
Authorization: Bearer your-access-tokenPOST /api/v1/sync/roles/to-keycloak
Authorization: Bearer your-access-tokenPOST /api/v1/sync/roles/from-keycloak
Authorization: Bearer your-access-tokenPOST /api/v1/sync/full/to-keycloak
Authorization: Bearer your-access-tokenPOST /api/v1/sync/full/from-keycloak
Authorization: Bearer your-access-token# Run all tests
go test ./...
# Run tests with coverage
go test -cover ./...
# Run tests with verbose output
go test -v ./...
# Run specific test package
go test ./internal/service -vThe project includes comprehensive unit tests with:
- Mocked dependencies using testify/mock
- Table-driven tests for multiple scenarios
- Error case testing for robust error handling
- Business logic validation in service layer tests
If you need to regenerate mocks:
# Install mockery if not already installed
go install github.com/vektra/mockery/v2@latest
# Generate mocks (configuration in .mockery.yml)
mockery- Domain Layer (
internal/domain/): Contains business entities, value objects, and domain errors - Repository Layer (
internal/repository/): Data access interfaces and GORM implementations - Service Layer (
internal/service/): Business logic and orchestration - Transport Layer (
internal/transport/http/): HTTP handlers, routing, and request/response mapping - Infrastructure (
internal/database/,internal/config/): External concerns like database and configuration
- Follow Go best practices and idioms
- Use gofmt and goimports for code formatting
- Write comprehensive tests for new features
- Follow the existing error handling patterns
- Use structured logging with appropriate log levels
- Validate all user inputs
- Use proper HTTP status codes and error responses
The application automatically runs migrations on startup. Database schema is defined in the domain models using GORM tags.
Build the Docker image:
docker build -t keycloak-iam-service .Run with Docker Compose:
docker-compose up -dSet these environment variables in production:
SERVER_ENVIRONMENT=production
DATABASE_HOST=your-db-host
DATABASE_PASSWORD=your-secure-password
KEYCLOAK_URL=https://your-keycloak-server.com
KEYCLOAK_REALM=your-realm
KEYCLOAK_CLIENT_ID=your-client-id
KEYCLOAK_CLIENT_SECRET=your-client-secret
KEYCLOAK_ADMIN_USER=admin
KEYCLOAK_ADMIN_PASS=your-admin-password
LOGGER_LEVEL=warn
LOGGER_FORMAT=json- Start Keycloak (using the provided docker-compose.yaml):
docker-compose up -d-
Access Keycloak Admin Console:
- URL: http://localhost:8080
- Username: admin
- Password: admin_password
-
Create a Realm (optional, or use 'master'):
- Go to Admin Console
- Click "Add realm"
- Enter realm name and create
-
Configure Client:
- Go to Clients
- Create new client with ID:
iam-service - Set Access Type:
confidential - Enable Service Accounts
- Copy the client secret for configuration
-
Test Integration:
# Start the IAM service
go run cmd/server/main.go
# Check health (should show Keycloak as healthy)
curl http://localhost:8080/health
# Test login
curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"admin_password"}'- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes following the project standards
- Add tests for new functionality
- Ensure all tests pass (
go test ./...) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
For questions and support, please open an issue in the GitHub repository.