Skip to content

Repository files navigation

Book Service β€” Spring Boot & Spring Security

A Spring Boot REST API demonstrating secure API development using Spring Security, authentication, authorization, JWT-based security, and layered application architecture.

The project provides a practical reference for building a backend service where APIs are protected using authentication and role-based authorization.


🎯 Problem Statement

Modern backend services cannot expose business APIs without considering authentication and authorization.

For example, a Book Management API may expose operations such as:

  • View books
  • Create books
  • Update books
  • Delete books

However, not every operation should be available to every user.

A typical requirement could be:

                     Book Service

                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚    Client   β”‚
                    β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
                           β–Ό
                  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                  β”‚ Authentication  β”‚
                  β”‚ & Authorization β”‚
                  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
               β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
               β”‚                       β”‚
               β–Ό                       β–Ό
          Read Operations         Write Operations
          USER / ADMIN               ADMIN
               β”‚                       β”‚
               β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β–Ό
                     Book Service

The problem this project addresses is:

How do we build a Spring Boot REST service where authentication and authorization are enforced consistently before requests reach the business layer?

The project demonstrates how Spring Security can be integrated into a REST API to establish a security boundary between external clients and application functionality.


πŸ—οΈ High-Level Architecture

The application follows a layered architecture with Spring Security acting as the security boundary.

flowchart TB

    Client["REST Client<br/>Postman / Browser / Application"]

    Security["Spring Security Filter Chain<br/>Authentication + Authorization"]

    Controller["REST Controller"]

    Service["Service Layer<br/>Business Logic"]

    Repository["Repository Layer<br/>Data Access"]

    DB[("Database")]

    Client -->|HTTP Request + Credentials / JWT| Security
    Security -->|Authorized Request| Controller
    Controller --> Service
    Service --> Repository
    Repository --> DB

    Security -.->|401 Unauthorized| Client
    Security -.->|403 Forbidden| Client
Loading

Request Flow

Client
  β”‚
  β”‚ HTTP Request
  β”‚
  β–Ό
Spring Security Filter Chain
  β”‚
  β”œβ”€β”€ Authentication
  β”‚
  β”œβ”€β”€ Token Validation
  β”‚
  β”œβ”€β”€ Authorization
  β”‚
  β–Ό
Controller
  β”‚
  β–Ό
Service
  β”‚
  β–Ό
Repository
  β”‚
  β–Ό
Database

The important architectural principle is:

Security is enforced before the request reaches the application business logic.


πŸ” Security Architecture

Spring Security provides the security boundary around the REST APIs.

                         HTTP Request
                              β”‚
                              β–Ό
                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                 β”‚ Spring Security Filter β”‚
                 β”‚        Chain            β”‚
                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
                     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”
                     β”‚                 β”‚
                     β–Ό                 β–Ό
                Authenticated?    Token Valid?
                     β”‚                 β”‚
                     β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β–Ό
                       Authorization
                              β”‚
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚                   β”‚
                    β–Ό                   β–Ό
                 Allowed             Denied
                    β”‚                   β”‚
                    β–Ό                   β”œβ”€β”€β–Ί 401
               Controller              β”‚
                                       └──► 403

Authentication

Authentication answers:

Who is the caller?

Authorization

Authorization answers:

What is the caller allowed to do?

Keeping these concepts separate is fundamental to designing secure APIs.


πŸͺͺ JWT Authentication

When JWT authentication is enabled, the client sends a token with the request:

Authorization: Bearer <JWT>

The request flow becomes:

Client
  β”‚
  β”‚ Authorization: Bearer JWT
  β–Ό
Spring Security
  β”‚
  β”œβ”€β”€ Extract JWT
  β”œβ”€β”€ Validate token
  β”œβ”€β”€ Validate signature
  β”œβ”€β”€ Extract user/roles
  └── Build SecurityContext
          β”‚
          β–Ό
       Controller

The application can then use the authenticated identity and authorities when evaluating access to protected endpoints.


πŸ‘₯ Authentication vs Authorization

A secure API typically needs both.

Authentication

Who are you?
      β”‚
      β–Ό
JWT / Credentials
      β”‚
      β–Ό
Authenticated User

Authorization

What can you do?
      β”‚
      β–Ό
Roles / Authorities
      β”‚
      β–Ό
Endpoint Access

Example:

USER
 β”œβ”€β”€ GET /books
 └── GET /books/{id}

ADMIN
 β”œβ”€β”€ GET    /books
 β”œβ”€β”€ POST   /books
 β”œβ”€β”€ PUT    /books/{id}
 └── DELETE /books/{id}

Adjust the exact endpoint/role mapping above to match the current security configuration in the project.


🧩 Application Architecture

The project follows a conventional Spring Boot layered architecture:

Controller
    β”‚
    β–Ό
Service
    β”‚
    β–Ό
Repository
    β”‚
    β–Ό
Database

Controller

Responsible for:

  • HTTP endpoints
  • Request mapping
  • Request/response handling
  • Validation boundaries

Service

Responsible for:

  • Business logic
  • Transaction boundaries
  • Domain operations

Repository

Responsible for:

  • Database access
  • Persistence operations
  • Query execution

Security Layer

Cross-cuts the request path before the controller:

Security
    β”‚
    β–Ό
Controller
    β”‚
    β–Ό
Service
    β”‚
    β–Ό
Repository

🧰 Technology Stack

Technology Purpose
Java Application development
Spring Boot Backend framework
Spring Web REST APIs
Spring Security Authentication & authorization
JWT Stateless authentication
Spring Data Persistence
Gradle / Maven Build automation
JUnit Testing

The repository is a Java-based Spring Boot project and is described on your GitHub profile as a book service with Spring Security enabled.


πŸ“‹ Prerequisites

Install:

  • JDK 25
  • Git
  • Gradle or Maven, depending on the project build configuration
  • An IDE such as IntelliJ IDEA or VS Code
  • Postman or another REST client

Verify Java:

java -version

πŸš€ Getting Started

1. Clone the repository

git clone https://github.com/ashutoshsahoo/book-service.git

cd book-service

2. Build the application

mvn clean package

3. Start the application

Gradle

mvn spring-boot:run

The application will start using the configured Spring Boot server port.


πŸ§ͺ API Testing

Use Postman, curl, or another REST client to interact with the API.

A typical API workflow is:

1. Authenticate
       β”‚
       β–Ό
2. Obtain JWT
       β”‚
       β–Ό
3. Send JWT in Authorization header
       β”‚
       β–Ό
4. Access protected Book APIs

Example:

Authorization: Bearer <JWT>

πŸ“š Book API

The service provides APIs for managing books.

Typical REST operations include:

Operation HTTP Method Purpose
Create POST Create a book
Read GET Retrieve books
Update PUT Update a book
Delete DELETE Delete a book

Example REST model:

{
  "title": "Designing Data-Intensive Applications",
  "author": "Martin Kleppmann"
}

The exact endpoint paths and request/response models should be kept synchronized with the controller implementation.


πŸ”’ HTTP Security Responses

A secure API should clearly distinguish authentication and authorization failures.

401 Unauthorized

The client has not successfully authenticated.

Examples:

Missing token
Invalid token
Expired token
Invalid credentials

403 Forbidden

The client is authenticated but does not have sufficient permissions.

Example:

Authenticated USER
        β”‚
        β–Ό
DELETE /books/10
        β”‚
        β–Ό
403 Forbidden

This distinction is important when designing and troubleshooting secured REST APIs.


πŸ›‘οΈ Security Principles Demonstrated

This project demonstrates:

  • Authentication
  • Authorization
  • JWT-based security
  • Stateless API security
  • Spring Security filter chain
  • Security context
  • Role/authority-based access control
  • Protected REST endpoints
  • HTTP 401 vs 403 handling

πŸ§ͺ Testing Strategy

Security-focused testing should cover both successful and unsuccessful scenarios.

Authentication Tests

βœ“ Valid credentials
βœ“ Invalid credentials
βœ“ Missing credentials
βœ“ Invalid JWT
βœ“ Expired JWT

Authorization Tests

βœ“ Authorized USER access
βœ“ Authorized ADMIN access
βœ“ USER attempting ADMIN operation
βœ“ Unauthenticated access

API Tests

βœ“ Create book
βœ“ Retrieve book
βœ“ Update book
βœ“ Delete book
βœ“ Invalid book request
βœ“ Non-existent book

πŸ” Troubleshooting

Application starts but API returns 401

Check:

Authorization: Bearer <JWT>

Also verify:

  • JWT is valid
  • JWT has not expired
  • Authorization header is present
  • Security configuration permits the endpoint

API returns 403

The request is authenticated, but the authenticated principal does not have the required authority/role.

Check the role/authority contained in the authenticated security context.


Application redirects to /error

For REST APIs, unexpected redirects to /error can often indicate an exception occurring during request processing or security handling.

Check the application logs for the original exception before troubleshooting the /error endpoint itself.


πŸ“ Project Structure

A typical structure for the service is:

book-service/
β”‚
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main/
β”‚   β”‚   β”œβ”€β”€ java/
β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   β”‚
β”‚   β”‚   └── resources/
β”‚   β”‚       β”œβ”€β”€ application.yml
β”‚   β”‚       └── ...
β”‚   β”‚
β”‚   └── test/
β”‚       └── ...
β”‚
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ pom.xml
└── README.md

🐳 Containerization

The application can be containerized using Docker.

Example:

docker build -t book-service:latest .

Run:

docker run \
  -p 8080:8080 \
  book-service:latest

For production deployments, consider:

  • Non-root containers
  • Multi-stage Docker builds
  • Minimal JRE images
  • Container vulnerability scanning
  • Resource limits
  • Health probes
  • Externalized configuration
  • Secret management

☸️ Kubernetes β€” Future Deployment

The service can be extended into a Kubernetes workload:

                  Kubernetes Cluster
                         β”‚
                  β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”
                  β”‚   Service   β”‚
                  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
                         β”‚
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β–Ό                     β–Ό
        Spring Boot Pod       Spring Boot Pod
              β”‚                     β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                         β–Ό
                     Database

Potential Kubernetes capabilities include:

  • Deployment
  • Service
  • ConfigMap
  • Secret
  • Readiness probe
  • Liveness probe
  • Horizontal Pod Autoscaler
  • Resource requests and limits
  • Ingress / Gateway API

πŸ“ˆ Production Hardening

For a production-grade Spring Security service, consider adding:

Security

  • OAuth 2.0 / OpenID Connect
  • External Identity Provider
  • Key rotation
  • Refresh-token strategy
  • Fine-grained authorities
  • Method-level security
  • CORS policy
  • CSRF strategy appropriate for the API
  • Rate limiting
  • Audit logging

Secrets

Do not store:

JWT secret
Database password
API keys
Private keys

directly in source control.

Use:

  • Kubernetes Secrets
  • HashiCorp Vault
  • Cloud secret managers
  • External Secrets Operator

Observability

Add:

  • Spring Boot Actuator
  • Micrometer
  • Prometheus
  • Grafana
  • OpenTelemetry
  • Distributed tracing
  • Structured logging

🎯 Learning Outcomes

After working through this project, you should understand:

  1. How a Spring Boot REST API is structured.
  2. How Spring Security intercepts HTTP requests.
  3. How authentication differs from authorization.
  4. How JWT enables stateless authentication.
  5. How roles/authorities control API access.
  6. How 401 and 403 differ.
  7. How security concerns can be separated from business logic.
  8. How a secured Spring Boot service can be containerized and deployed.

πŸš€ Possible Enhancements

The service can be evolved toward a production-grade backend by adding:

                    API Gateway
                         β”‚
                         β–Ό
                  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                  β”‚ Book Serviceβ”‚
                  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
                         β”‚
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β–Ό              β–Ό              β–Ό
       Database      Redis Cache     Kafka
                                         β”‚
                                         β–Ό
                                  Event Consumers

Potential extensions:

  • OAuth2 Resource Server
  • Keycloak / external Identity Provider
  • Redis caching
  • Kafka domain events
  • Outbox pattern
  • PostgreSQL
  • OpenTelemetry
  • Prometheus + Grafana
  • Docker
  • Kubernetes
  • CI/CD
  • Contract testing
  • Testcontainers

⭐ Key Takeaway

This project demonstrates a fundamental backend engineering principle:

Security should be treated as an architectural boundary, not as logic implemented independently inside every business operation.

Spring Security provides that boundary, while the application layers remain focused on their respective responsibilities:

                 Security Boundary
                        β”‚
                        β–Ό
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚   Controller    β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                       β–Ό
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚     Service     β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                       β–Ό
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚   Repository    β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                       β–Ό
                    Database

This repository serves as a practical reference for building secure Spring Boot REST APIs with authentication, authorization and JWT-based security.

About

A Spring Boot REST API demonstrating secure API development using Spring Security, authentication, authorization, JWT-based security, and layered application architecture. The project provides a practical reference for building a backend service where APIs are protected using authentication and role-based authorization.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Used by

Contributors

Languages