Skip to content

devberatzengin/OpenAuth-Service

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

46 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

OpenAuth-Service

FastAPI Python JWT Docker PostgreSQL Microservices License

A scalable, production-ready authentication microservice built with FastAPI. Database-agnostic design with clean architecture and enterprise-grade security.


🎯 Project Overview

OpenAuth-Service is a standalone authentication microservice designed to be integrated into distributed systems. It handles user registration, login, token generation, token validation, and role-based access control with industry-standard practices.

Why this service?

  • βœ… Microservices ready β€” Deploy independently
  • βœ… Database agnostic β€” Works with PostgreSQL, MongoDB, MySQL
  • βœ… JWT-based β€” Stateless authentication
  • βœ… Clean architecture β€” Testable and maintainable
  • βœ… Production hardened β€” Rate limiting, input validation, encryption

✨ Features

Authentication

  • πŸ” User registration with email verification
  • πŸ”‘ Secure login with password hashing (bcrypt)
  • 🎫 JWT token generation with configurable expiry
  • πŸ”„ Refresh token mechanism
  • πŸšͺ Logout with token blacklist

Authorization

  • πŸ‘€ Role-based access control (RBAC)
  • πŸ“‹ Permission management
  • πŸ›‘οΈ Scope-based authorization

Security

  • πŸ”’ Password hashing with bcrypt
  • 🚫 Rate limiting (Slowhttptest protection)
  • βœ”οΈ Input validation (Pydantic)
  • πŸ“ Audit logging
  • πŸ” CORS configuration
  • πŸ§ͺ CSRF protection ready

API Features

  • πŸ“š Auto-generated OpenAPI documentation
  • βœ… Request/response validation
  • πŸ” Structured error responses
  • πŸ“Š Health check endpoint

πŸš€ Quick Start

Prerequisites

  • Python 3.10+
  • Docker (optional)
  • PostgreSQL 13+ (or any database)

Installation

git clone https://github.com/devberatzengin/OpenAuth-Service.git
cd OpenAuth-Service

# Create virtual environment
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Setup environment
cp .env.example .env
# Edit .env with your database credentials

Running Locally

# Database migrations
alembic upgrade head

# Start service
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# API docs: http://localhost:8000/docs
# ReDoc: http://localhost:8000/redoc

Running with Docker

docker build -t openauth-service .
docker run -p 8000:8000 --env-file .env openauth-service

πŸ“š API Endpoints

Authentication

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

{
  "email": "user@example.com",
  "password": "SecurePass123!",
  "first_name": "John",
  "last_name": "Doe"
}

Response: 201 Created
{
  "id": "uuid",
  "email": "user@example.com",
  "access_token": "eyJ...",
  "token_type": "bearer",
  "expires_in": 3600
}
POST /api/v1/auth/login
{
  "email": "user@example.com",
  "password": "SecurePass123!"
}
POST /api/v1/auth/refresh
{
  "refresh_token": "eyJ..."
}
POST /api/v1/auth/logout
Authorization: Bearer <token>

User Management

GET /api/v1/users/me
Authorization: Bearer <token>

PUT /api/v1/users/me
Authorization: Bearer <token>
{
  "first_name": "Jane",
  "last_name": "Smith"
}

PATCH /api/v1/users/me/password
{
  "current_password": "old_pass",
  "new_password": "new_pass123!"
}

Admin Endpoints

GET /api/v1/admin/users
Authorization: Bearer <admin_token>

GET /api/v1/admin/users/{user_id}

PATCH /api/v1/admin/users/{user_id}/role
{
  "role": "admin"
}

DELETE /api/v1/admin/users/{user_id}

πŸ—οΈ Architecture

Clean Layers

app/
β”œβ”€β”€ main.py                 # FastAPI app
β”œβ”€β”€ config.py              # Settings (Pydantic)
β”œβ”€β”€ api/
β”‚   β”œβ”€β”€ v1/
β”‚   β”‚   β”œβ”€β”€ endpoints/
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.py
β”‚   β”‚   β”‚   β”œβ”€β”€ users.py
β”‚   β”‚   β”‚   └── admin.py
β”‚   β”‚   └── dependencies.py  # Dependency injection
β”œβ”€β”€ services/              # Business logic
β”‚   β”œβ”€β”€ auth_service.py
β”‚   β”œβ”€β”€ user_service.py
β”‚   └── token_service.py
β”œβ”€β”€ models/                # Database models (SQLAlchemy)
β”œβ”€β”€ schemas/               # Pydantic models
β”œβ”€β”€ database/              # DB connection, session
β”‚   └── base.py
β”œβ”€β”€ security/              # Hash, JWT, crypto
└── tests/
    β”œβ”€β”€ conftest.py        # Fixtures
    β”œβ”€β”€ test_auth.py
    └── test_users.py

Request Flow

HTTP Request
    ↓
Route Handler (API endpoint)
    ↓
Dependency Injection (auth verification)
    ↓
Service Layer (business logic)
    ↓
Database Layer (ORM)
    ↓
Response (JSON)

πŸ”’ Security Implementation

Password Hashing

# Using bcrypt with salt
from passlib.context import CryptContext

pwd_context = CryptContext(
    schemes=["bcrypt"],
    deprecated="auto",
    bcrypt__rounds=12
)

hashed = pwd_context.hash("password")
verified = pwd_context.verify("password", hashed)

JWT Tokens

import jwt
from datetime import datetime, timedelta

payload = {
    "sub": user_id,
    "email": email,
    "role": role,
    "exp": datetime.utcnow() + timedelta(hours=1)
}

token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
decoded = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])

Rate Limiting

from slowapi import Limiter

limiter = Limiter(key_func=get_remote_address)

@app.post("/auth/login")
@limiter.limit("5/minute")
def login(request: LoginSchema):
    # Max 5 login attempts per minute
    pass

πŸ§ͺ Testing

# Run all tests
pytest -v

# Run with coverage
pytest --cov=app tests/

# Specific test file
pytest tests/test_auth.py -v

Example Test

def test_user_registration(client):
    response = client.post(
        "/api/v1/auth/register",
        json={
            "email": "test@example.com",
            "password": "TestPass123!",
            "first_name": "Test",
            "last_name": "User"
        }
    )
    assert response.status_code == 201
    assert response.json()["email"] == "test@example.com"

πŸ“Š Database Schema

-- Users table
CREATE TABLE users (
    id UUID PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    role VARCHAR(50) DEFAULT 'user',
    is_active BOOLEAN DEFAULT TRUE,
    is_verified BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

-- Roles table
CREATE TABLE roles (
    id UUID PRIMARY KEY,
    name VARCHAR(50) UNIQUE NOT NULL,
    description TEXT
);

-- User roles junction
CREATE TABLE user_roles (
    user_id UUID REFERENCES users(id),
    role_id UUID REFERENCES roles(id),
    PRIMARY KEY (user_id, role_id)
);

-- Token blacklist (logout)
CREATE TABLE token_blacklist (
    id UUID PRIMARY KEY,
    token TEXT NOT NULL,
    blacklisted_at TIMESTAMP DEFAULT NOW(),
    expires_at TIMESTAMP NOT NULL
);

πŸš€ Deployment

Environment Variables

# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/openauth

# JWT
SECRET_KEY=your-super-secret-key-change-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60
REFRESH_TOKEN_EXPIRE_DAYS=7

# Security
CORS_ORIGINS=["http://localhost:3000"]
RATE_LIMIT=10/minute

# Email (optional)
SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-app-password

Production Checklist

  • Set strong SECRET_KEY
  • Enable HTTPS only
  • Configure CORS properly
  • Setup email verification
  • Enable rate limiting
  • Monitor logs and errors
  • Use managed database (not localhost)
  • Setup CI/CD pipeline

πŸ“ˆ Monitoring & Logging

import logging

logger = logging.getLogger(__name__)

@app.post("/auth/login")
def login(credentials: LoginSchema):
    logger.info(f"Login attempt for {credentials.email}")
    try:
        # auth logic
    except Exception as e:
        logger.error(f"Login failed: {str(e)}")

πŸ”„ Future Roadmap

  • OAuth 2.0 / OpenID Connect
  • Two-factor authentication (2FA)
  • Social login (Google, GitHub)
  • Permission scopes (fine-grained)
  • API key authentication
  • Service-to-service JWT
  • Audit logging dashboard
  • WebSocket token validation

🀝 Contributing

  1. Fork the repo
  2. Create feature branch (git checkout -b feature/new-auth)
  3. Write tests first
  4. Commit with clear messages
  5. Push and create Pull Request

πŸ“– Resources


About

Production-ready JWT authentication microservice built with FastAPI. Database-agnostic, clean architecture, rate limiting, and enterprise-grade security.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors