Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

Auth Service – DeviceHub

Authentication and authorization microservice for DeviceHub.

This service is responsible for:

  • User authentication (login)
  • User registration (signup)
  • JWT token generation and validation
  • Role-based access control (ADMIN / CLIENT)
  • Synchronization of user data with other microservices via Kafka

It acts as the internal Identity Provider for the system.


1. Overview

The Auth Service exposes public REST endpoints for:

  • Creating a new account
  • Authenticating existing users

After successful authentication, it returns a signed JWT token. All protected endpoints in the system rely on this token.

The service is:

  • Stateless (no server-side sessions)
  • Backed by PostgreSQL
  • Integrated with Kafka for user synchronization
  • Built with Spring Boot 3, Spring Security, JPA and jjwt

2. Architecture

Core Technologies

  • Java 17
  • Spring Boot 3
  • Spring Security (stateless JWT)
  • Spring Data JPA
  • PostgreSQL
  • Apache Kafka
  • jjwt (HS256 signing)
  • Bean Validation (Jakarta Validation)

High-Level Flow

Signup

  1. Client sends signup request.

  2. Auth Service:

    • Validates input
    • Hashes password (BCrypt)
    • Stores user in auth_users
    • Publishes USER_CREATED event to Kafka
    • Generates JWT
  3. JWT is returned to client.

SignUpPage.png

Login

  1. Client sends username + password.

  2. Spring Security authenticates using:

    • DAO Authentication Provider
    • Database lookup
    • BCrypt password verification
  3. JWT is generated and returned.

LoginPage.png


3. API Endpoints

Base path:

/api/auth

POST /api/auth/signup

Registers a new user.

Request

{
  "username": "john.doe",
  "email": "john@example.com",
  "password": "StrongPass1",
  "firstName": "John",
  "lastName": "Doe"
}

Validation Rules

  • Username: 3–50 characters

  • Email: valid format

  • Password:

    • Minimum 8 characters
    • At least one uppercase letter
    • At least one lowercase letter
    • At least one digit
  • First name: required

  • Last name: required

Response

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

HTTP 200 OK


POST /api/auth/login

Authenticates existing user.

Request

{
  "username": "john.doe",
  "password": "StrongPass1"
}

Response

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

HTTP 200 OK


4. JWT Design

The service generates signed JWT tokens using:

  • Algorithm: HS256
  • Secret: Base64-encoded secret from configuration
  • Expiration: configurable (default 1 hour)

JWT Claims

Standard:

  • sub → username
  • iat → issued at
  • exp → expiration

Custom:

  • role → ADMIN or CLIENT
  • userId → UUID

These claims allow downstream services to:

  • Identify the user
  • Apply role-based authorization
  • Avoid additional DB calls if trusted

5. Security Model

Stateless Authentication

  • No server-side sessions
  • Each request must include:
Authorization: Bearer <token>

Password Security

  • Passwords are hashed using BCrypt
  • Plain passwords are never stored
  • Password strength is validated using a custom validator

Role-Based Access

Each user has exactly one role:

  • ADMIN
  • CLIENT

Authorities are mapped as:

ROLE_ADMIN
ROLE_CLIENT

6. Database

Table: auth_users

Column Type Notes
id UUID Primary key
username TEXT Unique, not null
password TEXT BCrypt hash
role TEXT Stored as string enum

User IDs are generated at signup time.


7. Kafka Integration

Topic:

sync.users

Produced Events

Event: USER_CREATED

Payload:

{
  "eventType": "USER_CREATED",
  "id": "uuid",
  "username": "john.doe",
  "email": "john@example.com",
  "firstName": "John",
  "lastName": "Doe"
}

Purpose:

  • Synchronize user creation with other microservices (e.g. user-service)

Consumed Events

Auth Service listens to:

  • USER_UPDATED
  • USER_DELETED

On update:

  • Username may be updated locally.

On delete:

  • User is removed from auth database.

This ensures consistency between services.


8. Validation and Error Handling

All input DTOs use Bean Validation.

Custom exception handling ensures consistent error responses:

{
  "status": 409,
  "code": "USERNAME_ALREADY_TAKEN",
  "message": "Username already taken: john.doe"
}

Authentication failures return:

  • HTTP 401
  • Generic message (no sensitive details exposed)

9. Testing

The service includes:

  • Unit tests for:

    • AuthService
    • JwtService
  • Controller tests using MockMvc

  • Context load test

Tests validate:

  • Token generation and validation
  • Signup flow
  • Login flow
  • Event publishing
  • Authentication failure behavior

10. Configuration

application.yml

security:
  jwt:
    secret-key: ${SECURITY_JWT_SECRET_KEY}
    expiration-time: 3600000

The secret must be Base64-encoded.


Profiles

  • local
  • docker

Each profile defines:

  • Database connection
  • Kafka bootstrap servers
  • User service URL

11. Docker

Multi-stage Docker build:

  • Stage 1: Maven build
  • Stage 2: Runtime image (Temurin JDK 17)

Expose:

8081

Run example:

docker build -t auth-service .
docker run -p 8081:8081 auth-service

12. Observability

Swagger UI:

/swagger-ui.html

OpenAPI Docs:

/v3/api-docs

Actuator endpoints available under:

/actuator

13. Design Principles

  • Clear separation of layers (Controller → Service → Repository)
  • Stateless security
  • Strong password policy
  • Event-driven synchronization
  • Explicit error model
  • Unit-tested business logic

14. Limitations

Current design:

  • Single role per user
  • No refresh token mechanism
  • No token revocation mechanism
  • Kafka publish not transactional with DB
  • No distributed tracing yet

These are areas for future enhancement.


15. Summary

Auth Service is a stateless JWT-based authentication microservice built for a distributed system.

It provides:

  • Secure credential handling
  • Token-based authorization
  • Role enforcement
  • Event-driven synchronization with other services
  • Clean layering and test coverage

It is designed to be simple, clear, and extensible for a microservices environment.