A comprehensive .NET 9 authentication server with JWT tokens, role-based authorization, audit logging, and PostgreSQL database.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Client Layer β
βββββββββββββββββββ¬ββββββββββββββββββ¬ββββββββββββββββββ¬ββββββββββββ€
β Web Apps β Mobile Apps β Desktop Apps β APIs β
βββββββββββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββββ΄ββββββββββββ
β
βββββββββββββΌββββββββββββ
β Nginx (Port 80) β
β Reverse Proxy + β
β Load Balancer β
βββββββββββββ¬ββββββββββββ
β
βββββββββββββΌββββββββββββ
β Auth API (Port 5000) β
β ASP.NET Core 9 + β
β JWT + Identity β
βββββββββββββ¬ββββββββββββ
β
βββββββββββββββββββββββββΌββββββββββββββββββββββββ
β β β
βββββββββΌβββββββββ ββββββββββΌβββββββββ ββββββββββΌβββββββββ
β PostgreSQL β β Redis β β Email β
β (Port 5432) β β (Port 6379) β β Service β
β Primary DB + β β Caching + β β (SMTP/SendGrid) β
β User Data + β β Sessions β β β
β Audit Logs β β β β β
ββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β
βββββββββΌβββββββββ
β pgAdmin β
β (Port 5050) β
β DB Management β
ββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Presentation Layer β
β βββββββββββββββββββ βββββββββββββββββββ β
β β Controllers β β Middlewares β β
β β - AuthControllerβ β - JWT Auth β β
β β - UserControllerβ β - Error Handlerβ β
β β - RoleControllerβ β - Audit Logger β β
β β - HealthControllerβ β - CORS Policy β β
β βββββββββββββββββββ βββββββββββββββββββ β
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββ
β Application Layer β
β βββββββββββββββββββ βββββββββββββββββββ β
β β Services β β Interfaces β β
β β - AuthService β β - IAuthService β β
β β - UserService β β - IUserService β β
β β - RoleService β β - IRoleService β β
β β - AuditService β β - IAuditServiceβ β
β β - EmailService β β - IEmailServiceβ β
β βββββββββββββββββββ βββββββββββββββββββ β
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββ
β Domain Layer β
β βββββββββββββββββββ βββββββββββββββββββ β
β β Entities β β DTOs β β
β β - User β β - LoginDto β β
β β - Role β β - RegisterDto β β
β β - Permission β β - UserDto β β
β β - AuditLog β β - RoleDto β β
β β - UserRole β β - AuthResponseDtoβ β
β β - UserPermissionβ β - ResetPasswordDtoβ β
β βββββββββββββββββββ βββββββββββββββββββ β
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββ
β Infrastructure Layer β
β βββββββββββββββββββ βββββββββββββββββββ β
β β Data Access β β External APIs β β
β β - DbContext β β - SMTP Client β β
β β - Migrations β β - HTTP Clients β β
β β - Seeding β β - File Storage β β
β β - Connection β β - Third-party β β
β β Pooling β β Services β β
β βββββββββββββββββββ βββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- π JWT Authentication - Secure token-based authentication with refresh tokens
- π₯ Role-Based Authorization - Hierarchical permission system with custom roles
- π§ Email Integration - Password reset, welcome emails, and notifications
- οΏ½ Comprehensive Audit Logging - Track all user actions and system changes
- ποΈ PostgreSQL Database - ACID-compliant with automatic migrations
- π³ Full Docker Support - Complete containerization with orchestration
- π₯ Health Monitoring - Application and database health endpoints
- οΏ½ Interactive API Docs - Swagger/OpenAPI 3.0 with real-time testing
- οΏ½ Soft Delete Pattern - Data preservation with logical deletion
- π Enterprise Security - HTTPS, CORS, rate limiting, security headers
- β‘ Performance Optimized - Redis caching, connection pooling, async operations
- Framework: .NET 9.0 with ASP.NET Core
- Database: PostgreSQL 16 with Entity Framework Core 9
- Authentication: ASP.NET Core Identity + JWT Bearer tokens
- Containerization: Docker & Docker Compose
- Reverse Proxy: Nginx with rate limiting and security headers
- Caching: Redis for session management and performance
- Database UI: pgAdmin for database administration
- Documentation: Swagger/OpenAPI 3.0 with interactive UI
- Testing: xUnit with integration tests
- Logging: Serilog with structured logging
- Docker Desktop (Recommended approach)
- .NET 9 SDK (for local development)
- PostgreSQL 16+ (for local development)
- Git for version control
# 1. Clone repository
git clone <your-repo-url>
cd AuthenticationServer
# 2. Setup environment
cp .env.example .env
# Edit .env file with your configuration
# 3. Start all services (PostgreSQL, API, pgAdmin, Redis, Nginx)
docker compose up -d
# 4. Verify services are running
docker compose ps
# 5. Check API logs
docker compose logs -f authapi# Start all services in development mode
docker compose up -d
# Stop all services
docker compose down
# Restart specific service
docker compose restart authapi
# View real-time logs
docker compose logs -f authapi
# View all container status
docker compose ps# Start in production mode with all optimizations
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
# Scale API instances (load balancing)
docker compose up -d --scale authapi=3
# Update and restart services
docker compose pull && docker compose up -d# Rebuild API container
docker compose build authapi
# Force recreate containers (fresh start)
docker compose up -d --force-recreate
# Access container shell
docker compose exec authapi bash
# Access PostgreSQL directly
docker compose exec postgres psql -U postgres -d AuthenticationServerDb# Create new migration (inside container)
docker compose exec authapi dotnet ef migrations add MigrationName --project ../AuthenticationServer.Data
# Update database with latest migrations
docker compose exec authapi dotnet ef database update --project ../AuthenticationServer.Data
# Generate SQL script for migrations
docker compose exec authapi dotnet ef migrations script --project ../AuthenticationServer.Data| Service | URL | Purpose | Credentials |
|---|---|---|---|
| Authentication API | http://localhost:5000 | Main API endpoints | - |
| Swagger Documentation | http://localhost:5000/swagger | Interactive API testing | - |
| Health Checks | http://localhost:5000/health | System health monitoring | - |
| Detailed Health | http://localhost:5000/health/detailed | Comprehensive health info | - |
| pgAdmin | http://localhost:5050 | Database management UI | [email protected] / Admin@123456 |
| Nginx Proxy | http://localhost:80 | Production reverse proxy | - |
After initial setup, these accounts are automatically created:
| Role | Password | Permissions | |
|---|---|---|---|
| System Admin | [email protected] | Admin@123456 | Full system access |
# 1. Clone repository
git clone <your-repo-url>
cd AuthenticationServer
# 2. Setup PostgreSQL database
createdb AuthenticationServerDb
# Alternative: Use Docker PostgreSQL
docker run --name postgres-dev -e POSTGRES_PASSWORD=password -p 5432:5432 -d postgres:16
# 3. Configure connection string
# Edit src/AuthenticationServer.Api/appsettings.Development.json
{
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Port=5432;Database=AuthenticationServerDb;Username=postgres;Password=yourpassword;"
},
"Jwt": {
"Key": "your-super-secret-key-that-is-at-least-32-characters-long",
"Issuer": "AuthenticationServer",
"Audience": "AuthenticationServer",
"ExpireMinutes": 60
}
}
# 4. Restore dependencies
dotnet restore
# 5. Run database migrations
cd src/AuthenticationServer.Api
dotnet ef database update --project ../AuthenticationServer.Data
# 6. Start the application
dotnet run
# API will be available at: https://localhost:7138 and http://localhost:5138# Build entire solution
dotnet build
# Run all tests
dotnet test
# Run tests with coverage
dotnet test --collect:"XPlat Code Coverage"
# Restore packages
dotnet restore# Create new migration
dotnet ef migrations add MigrationName --project ../AuthenticationServer.Data
# Update database to latest migration
dotnet ef database update --project ../AuthenticationServer.Data
# Rollback to specific migration
dotnet ef database update PreviousMigrationName --project ../AuthenticationServer.Data
# Remove last migration (if not applied)
dotnet ef migrations remove --project ../AuthenticationServer.Data
# Drop entire database (CAUTION!)
dotnet ef database drop --project ../AuthenticationServer.Data
# Generate SQL script for migrations
dotnet ef migrations script --project ../AuthenticationServer.Data
# List all migrations
dotnet ef migrations list --project ../AuthenticationServer.Data# Watch for changes and auto-reload
dotnet watch run
# Run in specific environment
dotnet run --environment Production
# Enable detailed logging
dotnet run --verbosity diagnostic
# Format code
dotnet format
# Analyze code for issues
dotnet analyzePOST /api/auth/register
Content-Type: application/json
{
"email": "[email protected]",
"password": "SecurePassword123!",
"firstName": "John",
"lastName": "Doe"
}
POST /api/auth/login
Content-Type: application/json
{
"email": "[email protected]",
"password": "SecurePassword123!"
}POST /api/auth/forgot-password
Content-Type: application/json
{
"email": "[email protected]"
}
POST /api/auth/reset-password
Content-Type: application/json
{
"email": "[email protected]",
"otpCode": "123456",
"newPassword": "NewSecurePassword123!"
}POST /api/auth/refresh-token
Authorization: Bearer <refresh-token>
POST /api/auth/logout
Authorization: Bearer <access-token>GET /api/users
Authorization: Bearer <token>
GET /api/users/{id}
Authorization: Bearer <token>
PUT /api/users/{id}
Authorization: Bearer <token>
Content-Type: application/json
{
"firstName": "Updated Name",
"lastName": "Updated Last",
"email": "[email protected]"
}
DELETE /api/users/{id}
Authorization: Bearer <token>GET /api/roles
Authorization: Bearer <token>
POST /api/roles
Authorization: Bearer <token>
Content-Type: application/json
{
"name": "CustomRole",
"description": "Custom role description"
}
PUT /api/roles/{id}
Authorization: Bearer <token>
DELETE /api/roles/{id}
Authorization: Bearer <token>GET /health
# Returns: {"status":"Healthy","timestamp":"..."}
GET /health/detailed
Authorization: Bearer <token>
# Returns detailed system informationUser Input β Validation β Password Hashing β Database Storage β Email Verification β Account Activation
- User submits registration form with email, password, and profile info
- System validates input (email format, password strength, uniqueness)
- Password is hashed using ASP.NET Core Identity (PBKDF2)
- User record created in PostgreSQL with
IsEmailConfirmed = false - Welcome email sent with confirmation link (optional)
- Audit log entry created for registration event
Login Request β Credential Validation β JWT Generation β Token Response β Protected Resource Access
- User submits email/password credentials
- System validates credentials against hashed password in database
- Upon success, JWT access token (short-lived) and refresh token (long-lived) are generated
- Tokens returned to client with user profile information
- Client includes access token in Authorization header for subsequent requests
- Middleware validates JWT signature and extracts user claims
- Audit log entry created for successful login
Request + JWT β Token Validation β Claims Extraction β Role/Permission Check β Access Decision
- Client sends request with JWT token in Authorization header
- JWT middleware validates token signature and expiration
- User claims and roles extracted from token payload
- Controller/Action authorization attributes check required permissions
- Access granted or denied based on user's roles and permissions
- Audit log entry created for authorization events
User β UserRoles β Roles β RolePermissions β Permissions β Resource Access
- Users can have multiple Roles
- Roles contain multiple Permissions
- Permissions define specific actions (Read, Write, Delete, etc.)
- System evaluates user's effective permissions for each request
- Hierarchical roles supported (Admin inherits User permissions)
User Action β Service Layer β Audit Service β Database β Queryable Logs
- Every significant action triggers audit logging
- Captures: User ID, Action, Entity Type, Old Values, New Values, Timestamp, IP Address
- Stored in dedicated AuditLog table for compliance and security monitoring
- Supports querying and filtering for security analysis
- Automatic cleanup of old logs based on retention policies
Event Trigger β Email Template β SMTP Client β External Email Service β User Inbox
- System events trigger email notifications (registration, password reset, etc.)
- Templates used for consistent formatting and branding
- SMTP client sends emails through configured provider (Gmail, SendGrid, etc.)
- Supports both HTML and plain text formats
- Email queue for high-volume scenarios (production)
Code Changes β EF Migration β Version Control β Deployment β Auto-Apply β Database Updated
- Entity changes trigger new Entity Framework migrations
- Migrations stored in version control with application code
- On deployment, migrations automatically applied to target database
- Supports rollback to previous migration if needed
- Zero-downtime deployments with migration strategies
Source Code β Docker Build β Container Registry β Orchestration β Health Checks β Live System
- Application packaged into Docker containers with dependencies
- Multi-stage builds optimize image size and security
- Docker Compose orchestrates multiple services (API, DB, Cache, Proxy)
- Health checks ensure service availability and automatic restarts
- Environment-specific configurations through environment variables
- Horizontal scaling through container replication
- JWT Security: RSA/HMAC signatures, configurable expiration, secure refresh tokens
- Password Security: PBKDF2 hashing with salt, configurable complexity requirements
- API Security: HTTPS enforcement, CORS policies, rate limiting, input validation
- Database Security: Connection string encryption, SQL injection prevention, audit trails
- Caching: Redis for session data, user profiles, and frequently accessed data
- Database: Connection pooling, optimized queries, proper indexing
- API: Async/await patterns, response compression, pagination
- Monitoring: Health checks, structured logging, performance counters
- Health Checks: API health, database connectivity, external service dependencies
- Logging: Structured logging with Serilog, log levels, correlation IDs
- Metrics: Performance counters, request duration, error rates
- Alerting: Failed login attempts, system errors, performance degradation
This authentication server provides enterprise-grade security, scalability, and maintainability for modern applications. The modular architecture allows for easy customization and extension based on specific requirements.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to 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.
- Port conflicts: Change ports in docker-compose.yml
- Permission errors: Run Docker Desktop as administrator
- Build failures: Clear Docker cache with
docker system prune -f
- Connection failures: Verify PostgreSQL is running and connection string is correct
- Migration errors: Check database permissions and run
dotnet ef database dropto reset - Seed data issues: Verify email constraints and password requirements
- JWT errors: Check JWT configuration and ensure keys are properly set
- Login failures: Verify user exists and password meets complexity requirements
- Permission denied: Check user roles and ensure proper authorization policies
- Check the Issues page for known problems
- Review Discussions for community support
- Contact maintainers for critical security issues
POST /api/auth/register- Register new userPOST /api/auth/login- User loginPOST /api/auth/forgot-password- Request password resetPOST /api/auth/reset-password- Reset password with OTPPOST /api/auth/refresh-token- Refresh JWT tokenPOST /api/auth/logout- User logout
GET /api/user- Get all usersGET /api/user/{id}- Get user by IDPUT /api/user/{id}- Update userDELETE /api/user/{id}- Soft delete userPOST /api/user/{id}/assign-role- Assign role to user
GET /api/role- Get all rolesPOST /api/role- Create new rolePUT /api/role/{id}- Update roleDELETE /api/role/{id}- Delete role
GET /health- Health checkGET /health/detailed- Detailed health information
- User Registration: Allows new users to register with the system.
- User Login: Authenticates users and provides access tokens.
- Forgot Password: Enables users to initiate a password reset process.
- OTP Email Verification: Sends a one-time password to verify user email addresses.
- Password Reset: Allows users to reset their passwords securely.
- User Roles and Permissions: Manages user roles and associated permissions.
- Audit Log: Maintains a log of changes and actions performed on entities.
- Soft Delete: Implements a soft delete mechanism for entities.
- Access and Refresh Tokens: Utilizes OpenIdDict for token management.
-
src
- AuthenticationServer.Api: Contains the API controllers and entry point.
- AuthenticationServer.Core: Contains core business logic, entities, DTOs, and interfaces.
- AuthenticationServer.Services: Implements services for user, authentication, role, and audit management.
- AuthenticationServer.Data: Manages database context and repositories for data access.
- AuthenticationServer.Infrastructure: Contains configuration and extension methods for dependency injection.
-
tests
- AuthenticationServer.Tests: Contains unit tests for controllers and services.
- AuthenticationServer.IntegrationTests: Contains integration tests for the application.
- Clone the repository.
- Set up the PostgreSQL database and update the connection string in
appsettings.json. - Run the migrations to create the database schema.
- Start the application and access the API endpoints.
API documentation is available via Swagger. Once the application is running, navigate to /swagger to explore the available endpoints and their usage.
Contributions are welcome! Please open an issue or submit a pull request for any enhancements or bug fixes.
This project is licensed under the MIT License. See the LICENSE file for details.