Skip to content

Karinateii/SmartHub

Repository files navigation

SmartHub

.NET CI .NET Version License: MIT PRs Welcome

A production-ready RESTful API built with .NET 8 following Clean Architecture principles, featuring JWT authentication, security best practices, and modern development workflows.

Table of Contents

Features

Authentication & Authorization

  • JWT Token-based Authentication with refresh token support
  • Role-based Access Control (User, Admin)
  • Secure Password Hashing with BCrypt
  • Email Verification system ready
  • Token Refresh & Revocation mechanisms

Security

  • Rate Limiting on sensitive endpoints (login, register, refresh)
  • Environment-based Secret Management (no hardcoded secrets)
  • Git Pre-commit Hooks to prevent secret commits
  • Secure Token Storage with hashed refresh tokens
  • HTTPS Redirection enforced

Architecture & Code Quality

  • Clean Architecture (Domain, Application, Infrastructure, API layers)
  • Entity Framework Core with SQL Server
  • FluentValidation for request validation
  • Structured Logging with Serilog (Console + File)
  • Health Check Endpoints for monitoring
  • Exception Handling Middleware for centralized error management

Testing & CI/CD

  • Integration Tests with in-memory database
  • Unit Tests for business logic
  • GitHub Actions CI/CD (Ubuntu & Windows runners)
  • Automated JWT Secret Validation in CI pipeline

API Features

  • RESTful Design principles
  • Swagger/OpenAPI Documentation with XML comments
  • Consistent Response Formats
  • CORS Ready for frontend integration

Tech Stack

Backend Framework

  • .NET 8 - Latest LTS version
  • ASP.NET Core Web API - Modern web framework
  • Entity Framework Core 8 - ORM for database operations

Database

  • SQL Server - Production database
  • In-Memory Database - Integration testing

Security & Authentication

  • JWT Bearer Authentication - Stateless authentication
  • BCrypt.NET - Password hashing
  • Microsoft Identity - Claims-based security

Validation & Logging

  • FluentValidation - Request validation
  • Serilog - Structured logging

Testing

  • xUnit - Testing framework
  • WebApplicationFactory - Integration testing

DevOps

  • GitHub Actions - CI/CD pipeline
  • PowerShell Scripts - Development automation

Architecture

SmartHub follows Clean Architecture principles with clear separation of concerns:

┌─────────────────────────────────────────┐
│         SmartHub.Api (Presentation)     │
│  Controllers, Middleware, Configuration │
└──────────────────┬──────────────────────┘
                   │
┌──────────────────▼──────────────────────┐
│      SmartHub.Application (Use Cases)   │
│     DTOs, Interfaces, Validators        │
└──────────────────┬──────────────────────┘
                   │
┌──────────────────▼──────────────────────┐
│   SmartHub.Infrastructure (External)    │
│  DbContext, Repositories, Services      │
└──────────────────┬──────────────────────┘
                   │
┌──────────────────▼──────────────────────┐
│      SmartHub.Domain (Core Business)    │
│    Entities, Enums, Value Objects       │
└─────────────────────────────────────────┘

Key Benefits:

  • Testability: Business logic independent of external dependencies
  • Maintainability: Clear boundaries between layers
  • Flexibility: Easy to swap implementations (for example: change database)
  • Scalability: Clear separation enables team collaboration

See ARCHITECTURE.md for detailed architecture documentation

Getting Started

Prerequisites

Quick Start

1️⃣ Clone the repository

git clone https://github.com/Karinateii/SmartHub.git
cd SmartHub
  1. Run the setup script (recommended)
cd scripts
./setup-dev.ps1 -SetEnvVars

The script performs common development setup tasks:

  • Creates appsettings.json from the example template
  • Generates JWT secrets for local development
  • Sets environment variables for your session
  • Performs basic validation of your environment

3️⃣ Apply database migrations

dotnet ef database update --project SmartHub.Infrastructure --startup-project SmartHub.Api

4️⃣ Run the application

dotnet run --project SmartHub.Api

5️⃣ Access the API

  • API: https://localhost:7XXX (check console output for exact port)
  • Swagger UI: https://localhost:7XXX/swagger
  • Health Check: https://localhost:7XXX/health

Manual Setup (Alternative)

If you prefer manual configuration:

Set Environment Variables (PowerShell)

$env:JWT_KEY = "your-super-secret-key-at-least-32-characters-long"
$env:JWT_ISSUER = "SmartHub"
$env:JWT_AUDIENCE = "SmartHubClient"
$env:ADMIN_EMAIL = "admin@smarthub.com"
$env:ADMIN_PASSWORD = "SecurePass123!"

Update Connection String in SmartHub.Api/appsettings.json:

{
  "ConnectionStrings": {
    "SmartHubDatabase": "Server=(localdb)\\mssqllocaldb;Database=SmartHubDb;Trusted_Connection=true;MultipleActiveResultSets=true"
  }
}

API Documentation

Authentication Endpoints

Method Endpoint Description Rate Limit
POST /api/auth/register Register new user 3 req/hour
POST /api/auth/login Login with credentials 5 req/min
POST /api/auth/refresh Refresh access token 30 req/min
POST /api/auth/logout Revoke refresh token -

Example: Register User

Request:

POST /api/auth/register
Content-Type: application/json

{
  "firstName": "John",
  "lastName": "Doe",
  "email": "john.doe@example.com",
  "password": "SecurePass123!",
  "confirmPassword": "SecurePass123!"
}

Response:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "CfDJ8P+5K...",
  "expiresAt": "2025-11-26T15:30:00Z",
  "refreshTokenExpiry": "2025-12-03T14:30:00Z",
  "userId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "email": "john.doe@example.com",
  "fullName": "John Doe",
  "role": "User"
}

📖 See API_DOCUMENTATION.md for comprehensive API reference

Security

Secret Management

Never commit secrets! SmartHub uses environment variables for all sensitive configuration.

Required Environment Variables

# JWT Configuration (Required)
$env:JWT_KEY = "minimum-32-characters-for-hs256-security"
$env:JWT_ISSUER = "SmartHub"
$env:JWT_AUDIENCE = "SmartHubClient"

# Admin Seeding (Optional)
$env:ADMIN_EMAIL = "admin@smarthub.com"
$env:ADMIN_PASSWORD = "AdminSecure123!"

Pre-commit Hooks

Install Git hooks to prevent accidental secret commits:

cd scripts
./install-hooks.ps1

This validates that sensitive files aren't committed.

Secret Rotation

Local/Development:

$env:JWT_KEY = "new-secure-key-at-least-32-chars"
# Restart application

Production/CI:

  1. Update GitHub repository secrets: Settings → Secrets and variables → Actions
  2. Update JWT_KEY with a new secure value
  3. Redeploy application
  4. Consider token grace period or force user re-login

The CI pipeline validates JWT_KEY presence and length (≥32 chars)

Testing

Run All Tests

dotnet test

Run Specific Test Projects

# Unit Tests
dotnet test SmartHub.Tests/SmartHub.Tests.csproj --filter Category=Unit

# Integration Tests
dotnet test SmartHub.Tests/SmartHub.Tests.csproj --filter Category=Integration

Test Coverage

  • Authentication flow (register → login → refresh → logout)
  • Token generation and validation
  • Refresh token rotation
  • FluentValidation rules
  • Integration tests with in-memory database

Scripts

SmartHub includes automation scripts in the scripts/ directory:

Script Description
setup-dev.ps1 Initialize development environment
install-hooks.ps1 Install Git pre-commit hooks
pre-commit.ps1 Validate commits for secrets
smoke-test.ps1 Quick API health validation

Usage Examples

# Setup with environment variables
./scripts/setup-dev.ps1 -SetEnvVars

# Install security hooks
./scripts/install-hooks.ps1

# Run smoke tests after deployment
./scripts/smoke-test.ps1

Contributing

Contributions are welcome! Please read CONTRIBUTING.md for details on:

  • Code of conduct
  • Development workflow
  • Pull request process
  • Coding standards

License

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


For issues and feature requests, see: Report BugRequest Feature

About

Production-ready .NET 8 Web API with Clean Architecture, JWT authentication, and CI/CD

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published