Careeroza
Real World Example
ShopEase Security Requirements
Throughout this course we secure ShopEase, an online store like Flipkart or Myntra. Before writing any code, a real team writes down who may do what:
| Endpoint | Who can call it | Why |
|---|---|---|
GET /api/products, GET /api/categories | everyone | shoppers browse before logging in |
POST /api/auth/register | everyone | new customers must be able to sign up |
GET /api/cart, POST /api/orders | logged-in customers | carts and orders belong to a user |
POST/PUT/DELETE /api/products | admins only | only staff change the catalogue |
/actuator/health | everyone (load balancer) | health checks must not need a login |
A First Glimpse of the Config
package com.shopease.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/products/**", "/api/categories/**").permitAll()
.requestMatchers("/api/auth/register", "/actuator/health").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults())
.formLogin(Customizer.withDefaults());
return http.build();
}
}Every line of this class is explained in the coming modules. Notice there is no WebSecurityConfigurerAdapter: it was removed in Spring Security 6. Modern code declares a SecurityFilterChain bean.
The Result
Example
Anonymous browsing works, placing an order needs a login:
curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/api/products
curl -s -o /dev/null -w "%{http_code}\n" -X POST localhost:8080/api/orders
curl -s -o /dev/null -w "%{http_code}\n" -u asha:asha123 localhost:8080/api/cartExample output
200 401 200