Track C · Tutorial 2

Spring Security, Testing & Microservices

Chapter 26 · Backend Specialization
~3 hours Advanced JWT · JUnit · Spring Cloud · Docker

Overview

This tutorial takes your Spring Boot skills to the next level. You will secure APIs with Spring Security and JWT, write unit and integration tests with JUnit and Mockito, explore microservices with Spring Cloud, and containerise your application with Docker.

Why this matters: Security, testing, and microservices are essential for building robust, scalable, and production‑ready systems.

1. Spring Security (JWT)

Add Spring Security and JWT dependencies to your project.

// pom.xml dependencies spring-boot-starter-security jwt (jjwt)
// SecurityConfig.java @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeHttpRequests() .requestMatchers("/api/auth/**").permitAll() .anyRequest().authenticated() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); return http.build(); } }
// JwtService.java – generate and validate tokens public String generateToken(String username) { return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + 86400000)) .signWith(SignatureAlgorithm.HS256, SECRET_KEY) .compact(); }

2. Testing with JUnit & Mockito

Spring Boot uses JUnit for unit testing and Mockito for mocking dependencies.

// ProductServiceTest.java @ExtendWith(MockitoExtension.class) class ProductServiceTest { @Mock private ProductRepository productRepository; @InjectMocks private ProductService productService; @Test void findAll_shouldReturnProducts() { when(productRepository.findAll()).thenReturn(List.of(new Product())); List products = productService.findAll(); assertThat(products).hasSize(1); } }
// Integration test with @SpringBootTest @SpringBootTest @AutoConfigureMockMvc class ProductControllerIntegrationTest { @Autowired private MockMvc mockMvc; @Test void getProducts_shouldReturn200() throws Exception { mockMvc.perform(get("/api/products")) .andExpect(status().isOk()); } }

3. Microservices with Spring Cloud

Spring Cloud provides tools for building distributed systems.

  • Spring Cloud Netflix Eureka: Service discovery.
  • Spring Cloud Gateway: API gateway.
  • Spring Cloud OpenFeign: Declarative HTTP client.
// Eureka Server (Discovery Service) @SpringBootApplication @EnableEurekaServer public class DiscoveryServiceApplication { public static void main(String[] args) { SpringApplication.run(DiscoveryServiceApplication.class, args); } } // Eureka Client (Product Service) @SpringBootApplication @EnableDiscoveryClient public class ProductServiceApplication { ... }
// Feign Client @FeignClient(name = "inventory-service") public interface InventoryClient { @GetMapping("/api/inventory/{productId}") InventoryResponse getInventory(@PathVariable Long productId); }

4. Containerisation & Deployment

# Dockerfile FROM openjdk:17-jdk WORKDIR /app COPY target/*.jar app.jar EXPOSE 8080 ENTRYPOINT ["java", "-jar", "app.jar"]
docker build -t product-service . docker run -p 8080:8080 product-service

Quiz

Question 1

Which annotation enables Spring Security in a configuration class?

  • @EnableSecurity
  • @EnableWebSecurity
  • @SecurityConfiguration
  • @SpringSecurity
Show answer
B. @EnableWebSecurity.

Question 2

Which library is used for mocking in Spring Boot tests?

  • Mockk
  • Mockito
  • EasyMock
  • PowerMock
Show answer
B. Mockito (default with Spring Boot).

Question 3

Which Spring Cloud component is used for service discovery?

  • Spring Cloud Gateway
  • Spring Cloud Eureka
  • Spring Cloud Config
  • Spring Cloud Bus
Show answer
B. Spring Cloud Eureka.

Exercises

Exercise 1

Write a JUnit test for the ProductService.create method that verifies the product is saved and returned.

Sample answer
@Test void create_shouldSaveAndReturnProduct() { Product product = new Product(); product.setName("Test"); when(productRepository.save(any(Product.class))).thenReturn(product); Product result = productService.create(product); assertThat(result.getName()).isEqualTo("Test"); verify(productRepository).save(product); }

Exercise 2

Add a JWT authentication filter that validates the token and sets the security context.

Sample answer
public class JwtAuthenticationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String token = extractToken(request); if (token != null && jwtService.validateToken(token)) { String username = jwtService.extractUsername(token); Authentication auth = new UsernamePasswordAuthenticationToken(username, null, Collections.emptyList()); SecurityContextHolder.getContext().setAuthentication(auth); } chain.doFilter(request, response); } }

Homework

Homework 1

Extend the Bookstore API from Tutorial 1 with JWT authentication. Implement registration and login endpoints. Protect all write endpoints (POST, PUT, DELETE).

Sample outline
  • User model: User (id, username, password, roles)
  • AuthenticationController: /api/auth/register, /api/auth/login
  • SecurityConfig: Configure JWT filter and permit auth endpoints
  • BookController: Add @PreAuthorize("hasRole('ADMIN')") for write methods

Mini‑Project

Microservices: Order & Inventory

Build two microservices:

  • Order Service: Manages orders (GET, POST)
  • Inventory Service: Manages stock (GET, PUT)
  • Use Eureka for service discovery
  • Use Feign for inter‑service communication
  • Secure both with JWT
Sample outline
  • Eureka Server: Port 8761
  • Inventory Service: Port 8081, endpoints for stock check and update
  • Order Service: Port 8080, when creating an order, calls Inventory Service via Feign to reserve stock
  • JWT: Both services validate JWT via a shared filter

Tutorial Summary

You secured Spring Boot applications with JWT, wrote comprehensive tests with JUnit and Mockito, explored microservices with Spring Cloud, and containerised your application with Docker. You now have the skills to build secure, testable, and scalable enterprise systems.

Key takeaway: Spring Boot, combined with Spring Security and Spring Cloud, provides a complete, battle‑tested ecosystem for modern backend development.