Skip to content

Latest commit

 

History

History
346 lines (262 loc) · 9.45 KB

File metadata and controls

346 lines (262 loc) · 9.45 KB

Project Architecture

Secure

Spring Security Project

Table of Contents


Overview

This is a Spring Boot application with Spring Security integration that provides:

  • User authentication (JWT-based and OAuth2)
  • User registration and login
  • Password reset functionality
  • CSRF and session management
  • Demo data operations for testing database connectivity

REST Controllers

HelloController

Package: com.spring.Secure.Controller

A simple controller for health checks and basic security testing endpoints.

Endpoint Method Description Request Body Response
/healthcheck GET Health check endpoint that identifies authentication type None "Hello World" (String)
/csrf GET Returns CSRF token for the current request None CSRF token object
/sessionid GET Returns the current HTTP session ID None Session ID (String)
/ (root) POST Test POST endpoint None "Posting" (String)

Authentication: No specific authentication required (endpoint behavior depends on Spring Security configuration)


UserController

Package: com.spring.Secure.Controller

Main controller handling user authentication, registration, and password management. Uses JWT for token-based authentication.

Swagger Tag: User Service APIs - User registration, login, forgot password, reset password.

Endpoint Method Description Request Body Response Status Codes
/auth/register POST Register a new user RegisterDTO 201 CREATED or 400 BAD_REQUEST 201, 400
/auth/login POST Login using username and password UserDTO JWT token (String) 200, 401, 500
/auth/forgot-password POST Request password reset token ForgotPasswordRequest Reset token (String) 200, 404
/auth/reset-password POST Reset password using token ResetPasswordRequest "Password reset successful" 200, 400

Request/Response Details:

POST /auth/register

  • Request Body (RegisterDTO):
    {
      "username": "string (unique)",
      "password": "string",
      "email": "string",
      "role": ["string", "string"]
    }
  • Success Response: 201 CREATED
  • Error Response: 400 BAD_REQUEST (if username already exists)

POST /auth/login

  • Request Body (UserDTO):
    {
      "username": "string",
      "password": "string"
    }
  • Success Response: 200 OK with JWT token in body
  • Error Responses:
    • 401 UNAUTHORIZED - Invalid credentials
    • 500 INTERNAL_SERVER_ERROR - Authentication system error

POST /auth/forgot-password

  • Request Body (ForgotPasswordRequest):
    {
      "username": "string"
    }
  • Success Response: 200 OK with reset token
  • Note: In production, the reset token should be emailed to the user instead of returned in the response.
  • Error Response: 404 NOT_FOUND - Username not found

POST /auth/reset-password

  • Request Body (ResetPasswordRequest):
    {
      "token": "string (from forgot-password)",
      "newPassword": "string"
    }
  • Success Response: 200 OK
  • Error Response: 400 BAD_REQUEST - Invalid token or user not found

DemoDataController

Package: com.spring.Secure.Controller

Controller for testing database operations with demo data.

Base Path: /demo

Swagger Tag: Demo apis for testing db operations.

Security: Requires authentication (Bearer token or OAuth)

Endpoint Method Description Request Body Response
/demo/data GET Get all demo data from database None List<DemoData>
/demo/post POST Sample database insert operation None None (void)

Request/Response Details:

GET /demo/data

  • Success Response: 200 OK
    [
      {
        "id": "string",
        "name": "string",
        "email": "string"
      }
    ]

POST /demo/post

  • Description: Inserts a hardcoded demo record (name: "a", email: "a@b.com")
  • Success Response: 200 OK (empty body)

DTOs

RegisterDTO

{
  username: String,    // Required, must be unique
  password: String,    // Required
  email: String,       // Optional
  role: List<String>   // Required, list of roles (e.g., ["ROLE_USER", "ROLE_ADMIN"])
}

UserDTO

{
  username: String,    // Required
  password: String     // Required
}

ForgotPasswordRequest

{
  username: String     // Required, must exist in database
}

ResetPasswordRequest

{
  token: String,       // Required, obtained from forgot-password endpoint
  newPassword: String  // Required
}

Models

User Entity

  • Table Name: UserTable
  • Primary Key: username (String)
  • Fields:
    • username - Unique identifier
    • email - User email address
    • password - Hashed password
    • role - List of roles (stored in user_roles table)
    • passwordResetToken - Token for password reset
    • passwordResetTokenExpiresAt - Token expiration timestamp

DemoData Entity

  • Primary Key: id (auto-generated)
  • Fields:
    • id - Auto-generated identifier
    • name - Demo name
    • email - Demo email

API Endpoints Summary

Method Endpoint Controller Auth Required Description
GET /healthcheck HelloController No Health check
GET /csrf HelloController No Get CSRF token
GET /sessionid HelloController No Get session ID
POST / HelloController No Test POST
POST /auth/register UserController No Register user
POST /auth/login UserController No Login
POST /auth/forgot-password UserController No Request password reset
POST /auth/reset-password UserController No Reset password
GET /demo/data DemoDataController Yes Get all demo data
POST /demo/post DemoDataController Yes Insert demo data

Security Notes

  1. Authentication Mechanisms:

    • JWT (JSON Web Token) for stateless authentication
    • OAuth2 support for third-party authentication (Google, GitHub, etc.)
    • Session-based authentication
  2. Password Reset Flow:

    • User calls /auth/forgot-password with their username
    • System generates a reset token and stores it in the database
    • User calls /auth/reset-password with the token and new password
    • Production Note: Reset tokens should be sent via email, not returned in API response
  3. Role-Based Access Control:

    • Users are assigned roles during registration
    • Roles are stored in the user_roles table (One-to-Many relationship)
    • Common roles: ROLE_USER, ROLE_ADMIN

Project Structure

src/main/java/com/spring/Secure/
├── Config/           # Security and application configuration
├── Controller/       # REST API controllers
├── DTO/              # Data Transfer Objects
├── Exception/        # Custom exceptions
├── Filter/           # Security filters
├── Handler/          # Exception handlers
├── Model/            # JPA entities
├── Repo/             # Repository interfaces
├── Service/          # Business logic services
└── Utility/          # Utility classes

Development

Prerequisites

  • Java 17+
  • Maven 3.6+
  • MySQL/PostgreSQL database

Running the Application

mvn spring-boot:run

RSA Key Setup

This project uses RSA public/private key cryptography to sign and verify JWT tokens.

  • The private key is used to sign JWT tokens.
  • The public key is used to verify JWT tokens.
  • Never commit private keys to GitHub.

1. Create the Keys Directory

mkdir jwt-keys

2. Generate the RSA Private Key

openssl genpkey -algorithm RSA -out jwt-keys/private.pem -pkeyopt rsa_keygen_bits:2048

3. Generate the RSA Public Key

openssl rsa -pubout -in jwt-keys/private.pem -out jwt-keys/public.pem

Your directory structure should look like:

jwt-keys/
├── private.pem
└── public.pem

4. Protect Your Private Key

Add the following to your .gitignore:

# RSA Private Key
jwt-keys/private.pem

Important: Never commit or expose your private.pem file. The private key should only be used locally or stored securely in production.

5. Verify the Private Key

openssl rsa -in jwt-keys/private.pem -check

Security Note

The RSA keys generated above are intended for local development. For production environments, store private keys securely using a secret management solution and use separate key pairs for development and production.

API Documentation

Swagger/OpenAPI documentation is available at:

http://localhost:8080/swagger-ui.html