Back to Web Vulnerabilities: SQLi, XSS, CSRF, SSRF
Q9Question 9 of 9

Design Spring Security for a Production E-Commerce Application

Answer: Designing Spring Security for a production e-commerce application requires layered defense: OIDC for customer login, JWT for API authentication, resource ownership checks, service-to-service OAuth 2.0, CSRF/CORS configuration, and audit logging.

Key Concepts
  • Use an established identity provider (Keycloak, Auth0, AWS Cognito) for customer authentication via OIDC; do not build your own auth server.
  • Define multiple SecurityFilterChain beans: one for public APIs, one for customer APIs (JWT), one for admin portal (session + form login).
  • Enforce resource ownership at the service layer with @PreAuthorize: a customer must not access another customer's orders by changing the ID.
  • Use OAuth 2.0 Client Credentials with narrow scopes for service-to-service communication; each service validates tokens independently.
  • Never log passwords, bearer tokens, refresh tokens, or payment card numbers; use secrets management (Vault, AWS Secrets Manager) for credentials.
  • Combine URL-level security, method-level security, resource ownership checks, TLS, CSRF protection, CORS restrictions, and monitoring for defense in depth.

Definition

Designing Spring Security for a production e-commerce application requires layered defense: OIDC for customer login, JWT for API authentication, resource ownership checks, service-to-service OAuth 2.0, CSRF/CORS configuration, and audit logging.
  • Identity provider – an external service (Keycloak, Auth0, Cognito) that handles user registration, login, MFA, and token issuance; the e-commerce application is a relying party.
  • Resource ownership – verifying that the authenticated user owns the resource they are accessing (e.g., customer A cannot view customer B's orders).
  • Defense in depth – applying security at every layer: network (TLS, firewalls), transport (HTTPS), application (SecurityFilterChain), business logic (@PreAuthorize), and data (encryption, column-level access).
  • Least privilege – granting only the permissions required for each role: CUSTOMER gets ORDER_READ, ADMIN gets ORDER_REFUND, payment service gets PAYMENT_PROCESS.
  • Audit trail – logging every authentication attempt, authorization failure, and sensitive operation for compliance and forensics.

Designing security for an e-commerce platform is like securing a large bank with multiple branches. The main entrance has an identity check (OIDC login). Each department has its own access rules (SecurityFilterChain per module). The vault requires both the branch manager and the vault officer to be present (multi-layer authorization). Internal mail between branches is sealed and signed (mTLS, OAuth2 for service-to-service). Security cameras record everything (audit logging). And the bank never writes account PINs on sticky notes (no plaintext secrets).

Understanding the Concepts

What are the components of an e-commerce security design?

A production e-commerce platform typically includes:

  • Customer-facing web and mobile apps
  • REST APIs for products, orders, payments, and user profiles
  • An admin portal for operations staff
  • Background services (order processing, payment settlement, notification)
  • Service-to-service communication between microservices
  • A database with customer PII and payment information

Each component has different security requirements. The design must address authentication, authorization, data protection, and monitoring.

Step 1: Choose the authentication model

Use an established identity provider rather than building custom authentication:

YAML
# application.yml: OIDC login via Keycloak
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://auth.nationalbank.in/realms/ecommerce

For customer login: OAuth 2.0 Authorization Code with PKCE (web/mobile).
For admin login: OIDC with MFA enforced at the identity provider.
For service-to-service: OAuth 2.0 Client Credentials.

Never store passwords in your application database if you use an external identity provider.

Step 2: Define multiple SecurityFilterChain beans

JAVA
package com.bank.ecommerce.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.Customizer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class EcommerceSecurityConfig {

    private final BankAuthenticationEntryPoint entryPoint;
    private final BankAccessDeniedHandler accessDeniedHandler;

    public EcommerceSecurityConfig(BankAuthenticationEntryPoint entryPoint,
                                   BankAccessDeniedHandler accessDeniedHandler) {
        this.entryPoint = entryPoint;
        this.accessDeniedHandler = accessDeniedHandler;
    }

    // Chain 1: Public endpoints (health, product catalog)
    @Bean
    @Order(1)
    SecurityFilterChain publicChain(HttpSecurity http) throws Exception {
        return http
            .securityMatcher("/actuator/health", "/api/products/**", "/api/categories/**")
            .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
            .build();
    }

    // Chain 2: Customer API (JWT, stateless)
    @Bean
    @Order(2)
    SecurityFilterChain customerApiChain(HttpSecurity http) throws Exception {
        return http
            .securityMatcher("/api/**")
            .csrf(csrf -> csrf.disable())
            .sessionManagement(sess -> sess
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/orders/**").hasAuthority("SCOPE_orders.read")
                .requestMatchers("/api/payments/**").hasAuthority("SCOPE_payments.write")
                .requestMatchers("/api/profile/**").authenticated()
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
            .exceptionHandling(ex -> ex
                .authenticationEntryPoint(entryPoint)
                .accessDeniedHandler(accessDeniedHandler)
            )
            .build();
    }

    // Chain 3: Admin portal (session + form login)
    @Bean
    @Order(3)
    SecurityFilterChain adminChain(HttpSecurity http) throws Exception {
        return http
            .securityMatcher("/admin/**")
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/admin/login", "/admin/assets/**").permitAll()
                .requestMatchers("/admin/refunds/**").hasAuthority("ORDER_REFUND")
                .requestMatchers("/admin/users/**").hasRole("SUPER_ADMIN")
                .anyRequest().hasRole("ADMIN")
            )
            .formLogin(form -> form
                .loginPage("/admin/login")
                .defaultSuccessUrl("/admin/dashboard")
            )
            .build();
    }
}

Step 3: Enforce resource ownership

URL-level security checks roles. Resource ownership checks that the user actually owns the data they are accessing:

JAVA
package com.bank.ecommerce.security;

import com.bank.ecommerce.repository.OrderRepository;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

@Component("orderAuth")
public class OrderAuthorization {

    private final OrderRepository orderRepository;

    public OrderAuthorization(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    public boolean isOwner(Authentication auth, Long orderId) {
        return orderRepository.findById(orderId)
            .map(order -> order.getCustomerId().equals(auth.getName()))
            .orElse(false);
    }
}
JAVA
package com.bank.ecommerce.service;

import com.bank.ecommerce.model.Order;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class OrderService {

    @PreAuthorize("@orderAuth.isOwner(authentication, #orderId)")
    public Order getOrder(Long orderId) {
        return orderRepository.findById(orderId)
            .orElseThrow(() -> new OrderNotFoundException(orderId));
    }

    @PreAuthorize("hasRole('ADMIN') and hasAuthority('ORDER_REFUND')")
    public void refundOrder(Long orderId) {
        // Only admin with refund permission
    }
}

Without resource ownership checks, Priya (customer-123) could change the URL to view Rajesh's order (customer-456) simply by guessing the order ID. This is IDOR (Insecure Direct Object Reference), one of the OWASP top vulnerabilities.

Step 4: Secure service-to-service communication

Microservices communicate using OAuth 2.0 Client Credentials with narrow scopes:

JAVA
// Order Service calls Payment Service
// Token obtained via Client Credentials flow
// Scope: payments.process (only what it needs)
@Bean
SecurityFilterChain internalApiChain(HttpSecurity http) throws Exception {
    return http
        .securityMatcher("/internal/**")
        .csrf(csrf -> csrf.disable())
        .sessionManagement(sess -> sess
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        )
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/internal/payments/**")
                .hasAuthority("SCOPE_payments.process")
            .anyRequest().denyAll()
        )
        .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
        .build();
}

Each service validates tokens independently. Never trust a request just because it comes from the internal network.

Step 5: Define fine-grained authorities

Use specific authorities instead of broad roles:

AuthorityWho gets itWhat it allows
ORDER_READCustomer, AdminView order details
ORDER_CREATECustomerPlace a new order
ORDER_REFUNDAdmin (Refund Specialist)Process refunds
PAYMENT_PROCESSPayment Service (machine)Charge payment method
USER_READAdminView customer profiles
USER_DISABLESuper AdminDisable customer accounts
PRODUCT_UPDATECatalog AdminUpdate product listings

Never give a service or user more permissions than they need. The payment service should not have USER_DISABLE authority.

Step 6: Protect sensitive data

Rules for production:

  • Never log passwords, bearer tokens, refresh tokens, or full card numbers.
  • Store secrets in a vault (HashiCorp Vault, AWS Secrets Manager), not in application.properties.
  • Encrypt PII (name, email, phone) at rest using column-level encryption.
  • Use HTTPS for all communication (external and internal).
  • Mask sensitive data in error responses.
JAVA
// WRONG: Logging the bearer token
logger.info("Request from token: {}", request.getHeader("Authorization"));

// CORRECT: Log only the user identity, never the token
logger.info("Request from user: {} to {}",
    authentication.getName(),
    request.getRequestURI());

Step 7: Configure CSRF and CORS

JAVA
// CORS: allow only the frontend origin
@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(List.of("https://shop.nationalbank.in"));
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
    config.setAllowCredentials(false);

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", config);
    return source;
}

CSRF is disabled for the JWT API chain (stateless, no cookies). CSRF is enabled for the admin portal chain (session cookies).

Step 8: Add testing and monitoring

JAVA
@SpringBootTest
@AutoConfigureMockMvc
class OrderSecurityTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void unauthenticatedUserCannotAccessOrders() throws Exception {
        mockMvc.perform(get("/api/orders/1"))
            .andExpect(status().isUnauthorized());
    }

    @Test
    @WithMockUser(authorities = "SCOPE_orders.read")
    void authenticatedUserCanAccessOwnOrder() throws Exception {
        mockMvc.perform(get("/api/orders/1"))
            .andExpect(status().isOk());
    }

    @Test
    @WithMockUser(roles = "CUSTOMER")
    void customerCannotAccessAdminRefunds() throws Exception {
        mockMvc.perform(post("/admin/refunds/1"))
            .andExpect(status().isForbidden());
    }
}
  • Monitoring checklist:
  • Alert on repeated 401/403 from the same IP (brute force).
  • Alert on token validation failures (expired, wrong issuer).
  • Log every admin action (who, what, when, from where).
  • Monitor for unusual access patterns (customer accessing thousands of orders).

What is the complete security architecture?

LayerControl
NetworkVPC, security groups, private subnets for services
TransportTLS everywhere (HTTPS, mTLS for service-to-service)
AuthenticationOIDC via identity provider, JWT validation
URL authorizationSecurityFilterChain with requestMatchers
Method authorization@PreAuthorize with role and ownership checks
DataColumn encryption, no plaintext secrets, PCI compliance
MonitoringAudit logs, alerting on anomalies, SIEM integration
TestingSecurity tests in CI, dependency scanning, SAST/DAST

What should a senior engineer know?

  • A single annotation or a single JWT does not make an application secure. Security is layered.
  • The API gateway provides a useful perimeter (rate limiting, token validation), but each service must enforce its own authorization. If the gateway is bypassed, services must still reject unauthorized requests.
  • Plan for token revocation. JWT tokens are valid until expiry. For sensitive operations, consider short-lived tokens (5 minutes) with refresh tokens, or use opaque tokens with introspection.
  • Run dependency vulnerability scanning (Trivy, Snyk) in CI. A single vulnerable library can undermine all other security measures.
  • Conduct periodic security reviews and penetration testing. Automated tools catch known patterns; human testers find business logic flaws.

Visual Overview

DIAGRAM
┌─────────────────────────────────────────────────────────────┐
│                E-Commerce Security Architecture              │
└─────────────────────────────────────────────────────────────┘

  Customer                         Admin
  (Mobile/Web)                     (Browser)
      │                                │
      │ HTTPS                          │ HTTPS
      ▼                                ▼
┌──────────────┐               ┌──────────────┐
│  API Gateway │               │  Admin Portal│
│  Rate Limit  │               │  Form Login  │
│  JWT Forward │               │  Session+CSRF│
└──────┬───────┘               └──────┬───────┘
       │                              │
       ▼                              ▼
┌──────────────────────────────────────────────┐
│  SecurityFilterChain @Order(2): /api/**       │
│  JWT validation, SCOPE-based authorization    │
│  + @PreAuthorize resource ownership checks    │
├──────────────────────────────────────────────┤
│  SecurityFilterChain @Order(3): /admin/**     │
│  Form login, ROLE-based authorization         │
│  CSRF enabled, session management             │
└──────────────────────┬───────────────────────┘
                       │
         ┌─────────────┼─────────────┐
         ▼             ▼             ▼
   ┌──────────┐  ┌──────────┐  ┌──────────┐
   │ Order    │  │ Payment  │  │ Catalog  │
   │ Service  │  │ Service  │  │ Service  │
   │ JWT+OAuth│  │ JWT+OAuth│  │ JWT+OAuth│
   └──────────┘  └──────────┘  └──────────┘
         │             │             │
         │  Client Credentials       │
         │  + narrow scopes          │
         └─────────────┘             │
                                     │
   ┌─────────────────────────────────┘
   ▼
┌──────────────┐
│  Database    │
│  Encrypted   │
│  PII columns │
└──────────────┘

Key Takeaway

Designing Spring Security for a production e-commerce application is a system design question that tests whether you can combine individual security features into a coherent, layered architecture. Interviewers are not looking for a single configuration class; they want to see that you understand defense in depth.

The design starts with authentication: use an established identity provider for customer and admin login rather than building custom authentication. Then define multiple SecurityFilterChain beans: a public chain for product catalog, a JWT chain for customer APIs, and a session-based chain for the admin portal. Each chain has independent rules, authentication mechanisms, and CSRF/CORS settings.

The most commonly missed layer is resource ownership. URL-level security and role checks are not enough. If Priya can view her orders at /api/orders/101, she should not be able to view Rajesh's orders at /api/orders/102 just by changing the ID. The @PreAuthorize annotation with a custom authorization bean verifies ownership at the service layer, preventing IDOR vulnerabilities.

Service-to-service communication uses OAuth 2.0 Client Credentials with narrow scopes. Each service validates tokens independently and enforces its own authorization rules. The API gateway provides rate limiting and token forwarding, but it is not the only security checkpoint. If the gateway is bypassed, each service must still reject unauthorized requests.

The one sentence to remember: A secure e-commerce application layers identity provider authentication, URL-level SecurityFilterChain rules, method-level @PreAuthorize ownership checks, service-to-service OAuth 2.0 scopes, encrypted data storage, and audit logging, because no single annotation or token makes an application secure.

---

Share
Use ← → arrow keys to navigate