8000 GitHub - nutsp/keycloak-iam-service · GitHub
[go: up one dir, main page]

Skip to content

Navigation Menu

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Keycloak IAM Service

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.

Features

  • 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

Architecture

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

Quick Start

Prerequisites

  • Go 1.23+
  • PostgreSQL 12+
  • Docker and Docker Compose (optional)

Installation

  1. Clone the repository:
git clone <repository-url>
cd keycloak-iam-service
  1. Install dependencies:
go mod tidy
  1. Set up the database:
# Using Docker Compose (recommended)
docker-compose up -d postgres

# Or set up PostgreSQL manually and create database
createdb keycloak_iam
  1. Configure the application:
# Copy the example configuration
cp config.yaml config.local.yaml

# Edit config.local.yaml with your database settings
  1. Run database migrations:
go run cmd/server/main.go
# Migrations run automatically on startup
  1. Start the server:
go run cmd/server/main.go

The server will start on http://localhost:8080 by default.

Configuration

The application can be configured using:

  1. Configuration files (YAML): config.yaml, config.local.yaml
  2. Environment variables: All config keys can be set as env vars with _ separators

Configuration Options

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)

API Documentation

Base URL

http://localhost:8080/api/v1

Health Check

GET /health

Authentication

Login

POST /api/v1/auth/login
Content-Type: application/json

{
  "username": "admin",
  "password": "admin_password"
}

Refresh Token

POST /api/v1/auth/refresh
Content-Type: application/json

{
  "refresh_token": "your-refresh-token"
}

Logout

POST /api/v1/auth/logout
Content-Type: application/json

{
  "refresh_token": "your-refresh-token"
}

Get User Info

GET /api/v1/auth/userinfo
Authorization: Bearer your-access-token

Validate Token

POST /api/v1/auth/validate
Authorization: Bearer your-access-token

User Management

Note: All user management endpoints require authentication (Bearer token)

Create User

POST /api/v1/users
Content-Type: application/json

{
  "username": "johndoe",
  "email": "john@example.com",
  "first_name": "John",
  "last_name": "Doe",
  "password": "securepassword123"
}

Get User

GET /api/v1/users/{id}

Update User

PUT /api/v1/users/{id}
Content-Type: application/json

{
  "first_name": "Jane",
  "last_name": "Smith",
  "is_active": true
}

List Users

GET /api/v1/users?page=1&limit=10&search=john&is_active=true

Delete User

DELETE /api/v1/users/{id}

User Actions

POST /api/v1/users/{id}/activate
POST /api/v1/users/{id}/deactivate
POST /api/v1/users/{id}/verify
POST /api/v1/users/{id}/change-password

User Relationships

GET /api/v1/users/{id}/groups
GET /api/v1/users/{id}/roles
POST /api/v1/users/{id}/groups
POST /api/v1/users/{id}/roles

Group Management

Create Group

POST /api/v1/groups
Content-Type: application/json

{
  "name": "Administrators",
  "description": "System administrators group"
}

Group CRUD Operations

GET /api/v1/groups
GET /api/v1/groups/{id}
PUT /api/v1/groups/{id}
DELETE /api/v1/groups/{id}

Group Relationships

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}/roles

Role Management

Create Role

POST /api/v1/roles
Content-Type: application/json

{
  "name": "admin",
  "description": "Administrator role with full access"
}

Role CRUD Operations

GET /api/v1/roles
GET /api/v1/roles/{id}
PUT /api/v1/roles/{id}
DELETE /api/v1/roles/{id}

Role Assignments

GET /api/v1/roles/{id}/users
GET /api/v1/roles/{id}/groups
POST /api/v1/roles/{id}/users
POST /api/v1/roles/{id}/groups

Synchronization

Note: All synchronization endpoints require authentication and admin privileges

Sync Users to Keycloak

POST /api/v1/sync/users/to-keycloak
Authorization: Bearer your-access-token

Sync Users from Keycloak

POST /api/v1/sync/users/from-keycloak
Authorization: Bearer your-access-token

Sync Groups to Keycloak

POST /api/v1/sync/groups/to-keycloak
Authorization: Bearer your-access-token

Sync Groups from Keycloak

POST /api/v1/sync/groups/from-keycloak
Authorization: Bearer your-access-token

Sync Roles to Keycloak

POST /api/v1/sync/roles/to-keycloak
Authorization: Bearer your-access-token

Sync Roles from Keycloak

POST /api/v1/sync/roles/from-keycloak
Authorization: Bearer your-access-token

Full Sync to Keycloak

POST /api/v1/sync/full/to-keycloak
Authorization: Bearer your-access-token

Full Sync from Keycloak

POST /api/v1/sync/full/from-keycloak
Authorization: Bearer your-access-token

Testing

Run Unit Tests

# 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 -v

Test Structure

The 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

Generate Mocks

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

Development

Project Structure

  • 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

Code Standards

  • 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

Database Migrations

The application automatically runs migrations on startup. Database schema is defined in the domain models using GORM tags.

Deployment

Docker

Build the Docker image:

docker build -t keycloak-iam-service .

Run with Docker Compose:

docker-compose up -d

Environment Variables for Production

Set 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

Keycloak Setup

  1. Start Keycloak (using the provided docker-compose.yaml):
docker-compose up -d
  1. Access Keycloak Admin Console:

  2. Create a Realm (optional, or use 'master'):

    • Go to Admin Console
    • Click "Add realm"
    • Enter realm name and create
  3. 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
  4. 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"}'

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes following the project standards
  4. Add tests for new functionality
  5. Ensure all tests pass (go test ./...)
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For questions and support, please open an issue in the GitHub repository.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0