PadhaikoAll subjects

Spring Boot and Modern Web Development (part 2: 4.3–4.4)

Java Programming (ENCT 327)

Open in the Padhaiko app

4.3 API Development and Security

Building production-ready Spring Boot APIs requires clean REST endpoint semantics, consistent error handling, and strong authentication and authorization controls.

4.3.1 REST API design principles

REST (Representational State Transfer) models system data as resources identified by URIs and manipulated through standard HTTP methods.

  1. Resource-Oriented Plural Nouns: Name endpoints after resources, not actions—use GET /api/v1/students/42 and DELETE /api/v1/students/42, not /getStudent or /deleteStudent.
  2. Statelessness: Every HTTP request must contain all information needed to process it (credentials/JWT token, parameters); the server does not rely on in-memory HTTP sessions across requests.
  3. Safety and Idempotency:
    • Safe: Does not modify server state (GET, HEAD).
    • Idempotent: Calling the exact same request 1 time or N times leaves the server in the same final resource state (GET, PUT, DELETE). POST is not idempotent because repeating POST /api/orders creates multiple new orders.
  4. Input Validation & DTOs: Never bind JPA @Entity classes directly to @RequestBody. Use dedicated request/response DTO records annotated with Jakarta Bean Validation (@NotBlank, @Email, @Min, @Max) and trigger validation in the controller with @Valid.
  5. Versioning & Pagination: Version breaking API changes (/api/v1/...) and paginate collections (?page=0&size=20&sort=name,asc).
HTTP Methods, Semantics, and Standard Status Codes
MethodPurposeSafe?Idempotent?Typical Success CodesCommon Error Codes
GETRetrieve resource or listYesYes200 OK404 Not Found
POSTCreate a new resourceNoNo201 Created400 Bad Request, 409 Conflict
PUTFull replacement of resourceNoYes200 OK or 204 No Content400 Bad Request, 404 Not Found
PATCHPartial update of resourceNoDepends200 OK400 Bad Request, 404 Not Found
DELETERemove a resourceNoYes204 No Content404 Not Found

4.3.2 Handling exceptions in spring boot

Without centralized error handling, uncaught exceptions either return HTML "Whitelabel Error Pages" or leak internal stack traces. Spring Boot centralizes API error responses using @RestControllerAdvice and @ExceptionHandler.

Java
package edu.ioe.app.exception;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;

public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}

record ApiError(Instant timestamp, int status, String error, String message, String path) {}

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ApiError> handleNotFound(
            ResourceNotFoundException ex, HttpServletRequest req) {
        ApiError err = new ApiError(
                Instant.now(), 404, "Not Found", ex.getMessage(), req.getRequestURI());
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(err);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidation(
            MethodArgumentNotValidException ex, HttpServletRequest req) {
        Map<String, String> fieldErrors = new LinkedHashMap<>();
        ex.getBindingResult().getFieldErrors()
                .forEach(fe -> fieldErrors.put(fe.getField(), fe.getDefaultMessage()));

        Map<String, Object> body = new LinkedHashMap<>();
        body.put("timestamp", Instant.now());
        body.put("status", 400);
        body.put("errors", fieldErrors);
        body.put("path", req.getRequestURI());
        return ResponseEntity.badRequest().body(body);
    }
}

4.3.3 Overview of spring security for authentication and authorization

Definition

Authentication vs. Authorization in Spring Security

  1. Authentication (AuthN): Verifying who the caller is (via username/password, JWT Bearer token, or OAuth2 token). Failure returns HTTP 401 Unauthorized.
  2. Authorization (AuthZ): Verifying what an authenticated principal is permitted to do based on roles (ROLE_ADMIN, ROLE_STUDENT) or authorities (COURSE_WRITE). Failure returns HTTP 403 Forbidden.

Spring Security 6 Architecture

Spring Security protects endpoints via a Servlet Filter Chain (SecurityFilterChain) intercepting HTTP requests before they reach DispatcherServlet and @RestController:

Java
package edu.ioe.app.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
            // Stateless REST APIs using JWT disable cookie-based CSRF protection
            .csrf(csrf -> csrf.disable())
            .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/v1/auth/**", "/actuator/health").permitAll()
                .requestMatchers(HttpMethod.GET, "/api/v1/courses/**").permitAll()
                .requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            // Custom JwtAuthFilter would be inserted before UsernamePasswordAuthenticationFilter
            .build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Stateless JWT Authentication Flow

  1. Client sends POST /api/v1/auth/login with credentials.
  2. Server verifies password against BCrypt hash, signs a JWT (Header.Payload.Signature containing sub, roles, exp), and returns it.
  3. Client includes Authorization: Bearer <token> on subsequent requests.
  4. A custom OncePerRequestFilter validates the JWT signature and expiration, builds an Authentication object, and stores it in SecurityContextHolder.getContext().

4.4 Deployment and Project Work

Moving a Spring Boot project from a developer laptop to production requires reproducible packaging, environment separation, containerization, and runtime health checks.

4.4.1 Docker and containerization

Containerization packages an application together with its exact JDK/JRE runtime, libraries, and configuration into a portable Docker Image that runs identically across development, testing, and cloud servers.

AspectDocker ContainersVirtual Machines (VMs)
OS ArchitectureShares the host OS kernel via namespaces & cgroupsRuns a full guest OS per VM atop a hypervisor
Artifact SizeTens to hundreds of MB (e.g., 150 MB JRE image)Multiple GB (full OS disk image)
Startup TimeMilliseconds to a few secondsTens of seconds to minutes
Resource OverheadMinimal; high container density per hostHigher CPU and RAM overhead per guest OS
Isolation LevelProcess-level OS isolationHardware-level virtualization isolation

Multi-Stage Dockerfile for Spring Boot

A multi-stage build uses a full JDK + Maven image in Stage 1 to compile and package the JAR, then copies only the built JAR into a minimal JRE runtime image in Stage 2, shrinking image size and reducing attack surface:

Text
# Stage 1: Build executable JAR with Maven and JDK 21
FROM maven:3.9-eclipse-temurin-21 AS builder
WORKDIR /build
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src ./src
RUN mvn clean package -DskipTests

# Stage 2: Minimal JRE runtime image
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
COPY --from=builder /build/target/*.jar app.jar
USER appuser
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

4.4.2 Packaging and deploying a Spring Boot application

  1. Executable Fat JAR vs. WAR:
    • mvn clean package (or ./gradlew bootJar) produces a self-contained executable Fat/Uber JAR containing BOOT-INF/classes (application classes), BOOT-INF/lib (all dependencies including embedded Tomcat), and Spring Boot's loader. Run anywhere with java -jar target/app.jar.
    • WAR packaging (SpringBootServletInitializer) is used only when deploying into an external standalone servlet container (such as an existing Tomcat/WildFly server).
  2. Profiles and Externalized Secrets:
    • Separate environment settings into application-dev.yml (local H2/Postgres, debug SQL) and application-prod.yml (production pool sizes, strict logging). Activate via SPRING_PROFILES_ACTIVE=prod or --spring.profiles.active=prod.
    • Pass database passwords, JWT signing keys, and API tokens via environment variables (SPRING_DATASOURCE_PASSWORD), never committed to Git.
  3. Observability with Spring Boot Actuator:
    • Adding spring-boot-starter-actuator exposes production endpoints such as /actuator/health (used by Docker HEALTHCHECK and Kubernetes readiness/liveness probes) and /actuator/metrics.
  4. End-to-End Project Deployment Checklist:
    • Run automated unit & integration tests (mvn test).
    • Build JAR (mvn clean package) -> Build Docker image (docker build -t ioe-app:1.0 .) -> Run with externalized env config and database (docker compose up -d) -> Verify /actuator/health returns {"status":"UP"}.

Worked Examples

Example 4.4

4.4

Using the SecurityConfig defined in Section 4.3.3:

Determine the HTTP outcome (200 OK, 401 Unauthorized, or 403 Forbidden) for each of the following 4 requests:

  1. Unauthenticated GET /api/v1/courses/ENCT327
  2. Unauthenticated POST /api/v1/courses
  3. Authenticated user with ROLE_STUDENT calling GET /api/v1/admin/reports
  4. Authenticated user with ROLE_ADMIN calling GET /api/v1/admin/reports

Recall Spring Security's rule evaluation order: rules are matched top-to-bottom, and the first matching rule wins.

  • Request 1 (GET /api/v1/courses/ENCT327, anonymous): Matches rule 2 (GET + /api/v1/courses/** -> permitAll()), so it is allowed -> 200 OK (assuming course exists).
  • Request 2 (POST /api/v1/courses, anonymous): Does not match rule 1; does not match rule 2 because HTTP method is POST (not GET); does not match rule 3; falls through to anyRequest().authenticated(). Because caller has no authentication, Spring returns 401 Unauthorized.

Evaluate the remaining two authenticated requests:

  • Request 3 (GET /api/v1/admin/reports, ROLE_STUDENT): Matches rule 3 (hasRole("ADMIN")). The caller is authenticated, so AuthN passes, but lacks ROLE_ADMIN, so AuthZ fails -> 403 Forbidden.
  • Request 4 (GET /api/v1/admin/reports, ROLE_ADMIN): Matches rule 3 and satisfies hasRole("ADMIN") -> 200 OK.
Answer:
  1. GET /api/v1/courses/ENCT327 (anonymous): 200 OK (permitAll()).
  2. POST /api/v1/courses (anonymous): 401 Unauthorized (unauthenticated on anyRequest().authenticated()).
  3. GET /api/v1/admin/reports (ROLE_STUDENT): 403 Forbidden (authenticated, lacks ADMIN role).
  4. GET /api/v1/admin/reports (ROLE_ADMIN): 200 OK.
Example 4.5

4.5

A team initially packaged their Spring Boot app inside a single-stage Dockerfile based on a full Maven + JDK image (520 MB), plus 45 MB application Fat JAR and 60 MB cached Maven .m2 dependencies = 625 MB total image size. They refactor to a multi-stage Dockerfile using eclipse-temurin:21-jre-alpine (140 MB base JRE) copying only the 45 MB Fat JAR. Compute the final multi-stage image size, the MB saved, and the percentage size reduction.

Compute the multi-stage final image size (Stage 1's JDK, Maven binary, and .m2 cache are discarded and excluded from Stage 2): finalSize = 140 MB + 45 MB = 185 MB.

Compute size saved and percentage reduction relative to the 625 MB single-stage image:

  • MB saved: 625 - 185 = 440 MB.
  • Percentage reduction: (440 / 625) * 100 = 70.4%.
Answer:

The multi-stage Docker image is 185 MB (down from 625 MB), saving 440 MB—a 70.4% reduction in image size.

Example 4.6

4.6

How should a student answer the past exam question: "Explain centralized exception handling in Spring Boot using @RestControllerAdvice and @ExceptionHandler, and describe how Bean Validation errors are returned cleanly"?

Explain the Problem and Solution Pattern: Start by stating that scattering try-catch blocks across every controller duplicates code and risks returning inconsistent errors or stack traces. @RestControllerAdvice creates a global interceptor across all @RestControllers, while @ExceptionHandler(ExceptionClass.class) maps specific exceptions to structured JSON error payloads and HTTP status codes.

Show Two Concrete Handlers: Write a compact @RestControllerAdvice snippet handling (1) a custom ResourceNotFoundException -> 404 Not Found, and (2) MethodArgumentNotValidException (triggered by @Valid @RequestBody) -> 400 Bad Request extracting field error messages from ex.getBindingResult().getFieldErrors().

Answer:

A full-mark answer motivates centralized handling (DRY, no leaked stack traces), defines @RestControllerAdvice and @ExceptionHandler, and shows handlers mapping ResourceNotFoundException to 404 and @Valid MethodArgumentNotValidException field errors to a structured 400 Bad Request JSON body.


Exercises

Practice Exercises — API Security & Deployment

Question 1

Explain idempotency and safety in REST API design. Classify GET, POST, PUT, and DELETE according to both properties, and give an example of how repeating a non-idempotent request can cause a bug.

Definitions and Classification:

  • A safe HTTP method does not alter server state (GET).
  • An idempotent HTTP method yields the same final resource state whether executed once or multiple times (GET, PUT, DELETE).
  • POST is neither safe nor idempotent; PUT and DELETE are idempotent but not safe; GET is both safe and idempotent.

Concrete Bug from Non-Idempotency: If a client retries a timed-out POST /api/payments request without an idempotency key, the server processes the creation twice, charging the user twice or inserting two duplicate payment records. By contrast, retrying PUT /api/orders/10/status or DELETE /api/orders/10 leaves order 10 in the exact same state.

Answer:

GET is safe and idempotent; PUT and DELETE are unsafe but idempotent; POST is neither safe nor idempotent. Retrying a POST request after a network timeout can create duplicate resources or double charges because POST is non-idempotent.

Question 2

Write a @RestControllerAdvice handler for MethodArgumentNotValidException and ResourceNotFoundException, and show how a DTO record CreateUserReq(@NotBlank String name, @Email String email) {} triggers validation in a @PostMapping controller method.

Controller with @Valid DTO:

Java
record CreateUserReq(@NotBlank String name, @Email String email) {}

@PostMapping("/api/v1/users")
public ResponseEntity<CreateUserReq> create(@Valid @RequestBody CreateUserReq req) {
    return ResponseEntity.status(HttpStatus.CREATED).body(req);
}

Global @RestControllerAdvice:

Java
@RestControllerAdvice
public class ApiExceptionAdvice {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<Map<String, Object>> onNotFound(ResourceNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(Map.of("status", 404, "message", ex.getMessage()));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> onValidation(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new LinkedHashMap<>();
        ex.getBindingResult().getFieldErrors()
                .forEach(e -> errors.put(e.getField(), e.getDefaultMessage()));
        return ResponseEntity.badRequest().body(errors);
    }
}
Answer:

Annotating the @RequestBody DTO parameter with @Valid causes Spring MVC to throw MethodArgumentNotValidException on constraint violations, which @RestControllerAdvice catches via @ExceptionHandler and formats into 400 Bad Request (or 404 Not Found for ResourceNotFoundException).

Question 3

Distinguish between Authentication and Authorization in Spring Security, state which HTTP status codes (401 vs. 403) correspond to failures in each, and explain why stateless REST APIs configure SessionCreationPolicy.STATELESS with JWT and BCryptPasswordEncoder.

Authentication vs. Authorization (401 vs. 403):

  • Authentication verifies identity (e.g., validating username/password or JWT signature); failure returns 401 Unauthorized.
  • Authorization checks whether an already-authenticated user possesses the required role/authority (e.g., hasRole("ADMIN")); failure returns 403 Forbidden.

Why STATELESS, JWT, and BCryptPasswordEncoder:

  • SessionCreationPolicy.STATELESS instructs Spring Security not to create or store server-side HttpSessions, enabling horizontal scaling across multiple backend replicas; every request carries its signed JWT in Authorization: Bearer <token>.
  • BCryptPasswordEncoder hashes passwords with per-user random salts and an adaptive cost factor, protecting stored credentials even if the database is leaked.
Answer:

Authentication verifies identity (401 Unauthorized on failure) and Authorization verifies permissions (403 Forbidden on failure). Stateless REST services disable HTTP sessions (STATELESS), validate signed JWTs per request, and hash stored passwords with BCryptPasswordEncoder.

Question 4

Compare Docker containers and Virtual Machines (VMs), and explain how a multi-stage Dockerfile optimizes a Spring Boot image. If a single-stage JDK image weighs 580 MB and a multi-stage jre-alpine image (148 MB) copies a 38 MB Fat JAR, compute the percentage size reduction.

Containers vs. VMs & Multi-Stage Optimization:

  • VMs bundle an entire guest OS atop a hypervisor (gigabytes, slow boot), whereas containers share the host OS kernel and isolate processes via namespaces/cgroups (megabytes, near-instant startup).
  • A multi-stage Dockerfile compiles the JAR in a maven + jdk builder stage and copies only app.jar into a minimal jre-alpine final stage, leaving build tools, source files, and .m2 caches behind.

Image Size Reduction Calculation:

  • Multi-stage total size: 148 + 38 = 186 MB.
  • Size saved: 580 - 186 = 394 MB.
  • Percentage reduction: (394 / 580) * 100 = 67.93%.
Answer:

Containers share the host kernel for lightweight isolation compared to full-OS VMs, and multi-stage builds drop build-time JDK/Maven layers from the final runtime image. The multi-stage image is 186 MB, saving 394 MB (67.93% reduction).

Question 5

Contrast executable Fat JAR vs. WAR packaging in Spring Boot, and explain the roles of Spring Profiles (application-prod.yml), environment variables, and Spring Boot Actuator (/actuator/health) during deployment.

Fat JAR vs. WAR Packaging:

  • A Fat (Uber) JAR packages application classes, all third-party libraries, and an embedded server (Tomcat) into one runnable archive (java -jar app.jar), ideal for Docker and cloud microservices.
  • A WAR excludes the embedded server (or marks it provided) and deploys into an external standalone servlet container.

Profiles, Environment Variables, and Actuator:

  • Spring Profiles isolate environment-specific settings (dev vs. prod) switched via SPRING_PROFILES_ACTIVE.
  • Environment variables inject secrets (DB passwords, JWT keys) at runtime without committing credentials into source control.
  • Spring Boot Actuator exposes /actuator/health and /actuator/metrics so Docker, load balancers, and Kubernetes can automatically probe container readiness and liveness.
Answer:

Fat JARs bundle the app and embedded Tomcat into one self-contained java -jar artifact (preferred for containers), whereas WARs deploy to external servlet servers. Spring Profiles separate environment configurations, environment variables keep secrets out of Git, and Actuator (/actuator/health) provides automated health probes.

← Spring Boot and Modern Web Development (part 1: 4.1–4.2)Concurrency and Performance →