Spring Security

 

Spring Security is the standard security framework in the Spring ecosystem. It provides authentication, authorization, and protection against common attacks, making it essential for securing Spring Boot microservices.



What is Spring Security?

  • A powerful and customizable security framework for Java & Spring applications.

  • Works with Web Apps, REST APIs, and Microservices.

  • Handles:

    • Authentication → Who are you?

    • Authorization → What can you access?

  • Shields apps from:

    • CSRF (Cross-Site Request Forgery)

    • XSS (Cross-Site Scripting)

    • Session Fixation

    • Clickjacking

    • Brute force & injection attacks (via filters & password encoding)



Core Features of Spring Security

1. Authentication (Identity Verification)

Supports multiple mechanisms:

  • In-Memory Authentication

    @Bean public UserDetailsService userDetailsService() { UserDetails user = User.withUsername("admin") .password(passwordEncoder().encode("password")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user); }
  • Database Authentication (JDBC/JPA)

  • LDAP Authentication

  • OAuth2 & OpenID Connect (Google, GitHub, Keycloak, Okta, Auth0, etc.)

  • JWT (JSON Web Tokens) → Used for stateless microservices.


2. Authorization (Access Control)

  • Role-Based Access Control (RBAC)
    Example: ROLE_USER, ROLE_ADMIN

    @PreAuthorize("hasRole('ADMIN')") public String adminAction() { ... }
  • Permission/Authority-Based Access
    Example: USER_READ, USER_WRITE

    @PreAuthorize("hasAuthority('USER_READ')") public User getUser(Long id) { ... }
  • Method-Level Security

    • @PreAuthorize, @PostAuthorize, @Secured

    • @EnableMethodSecurity (Spring Boot 3+)


3. Security Filter Chain

  • Every request flows through a chain of filters.

  • Example: UsernamePasswordAuthenticationFilter, BearerTokenAuthenticationFilter.

  • Configure via SecurityFilterChain bean (new approach replacing WebSecurityConfigurerAdapter).

        @Bean         SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {         http.csrf().disable()         .authorizeHttpRequests(auth -> auth         .requestMatchers("/admin/**").hasRole("ADMIN")         .anyRequest().authenticated()         )         .oauth2Login(); // OAuth2 example         return http.build();         }


4. Integration with Spring Boot

  • Auto-configuration → adds default login page & security rules.

  • Can easily override with custom SecurityFilterChain.

  • Works seamlessly with:

    • Spring Data JPA (user storage)

    • Spring Cloud Gateway (API Gateway security)

    • Spring Session (shared sessions in distributed apps)


5. Defenses Against Attacks

  • CSRF Protection (enabled by default for web forms).

  • Password Encoding with BCryptPasswordEncoder.

  • HTTPS/SSL Enforcement (force https:// for requests).

  • Clickjacking Protection (X-Frame-Options).

  • Rate Limiting & Throttling (via Spring Cloud Gateway / Resilience4j).

  • CORS Configurations for microservices:

    http.cors(cors -> cors.configurationSource(request -> { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("http://frontend-app.com"); config.addAllowedMethod("*"); return config; }));



Advanced Features for Microservices

  • Stateless Security with JWT → Each request carries a token. No session needed.

  • OAuth2 Resource Server → Secure REST APIs with tokens issued by Identity Providers.

    @Bean SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception { http.oauth2ResourceServer(oauth2 -> oauth2.jwt()); return http.build(); }
  • Single Sign-On (SSO) → Central login with Keycloak/Okta across multiple services.

  • API Gateway Security (Spring Cloud Gateway) → Centralized authentication, rate limiting, IP whitelisting.

  • Service-to-Service Authentication → Use mutual TLS or service accounts.

  • Custom Security Context → Store user details, tenant info, request metadata.



Spring Security in Spring Boot Microservices (Best Practices)

  • Use OAuth2 + JWT for microservices authentication.

  • Centralize Authentication at the API Gateway level.

  • Enable Method-Level Security for fine-grained access control.

  • Secure Sensitive Endpoints (/actuator, /admin).

  • Use Strong Password Encoding (BCryptPasswordEncoder).

  • Enable HTTPS with self-signed or CA certificates.

  • Apply Rate Limiting & IP Filtering at the gateway.

  • Use CORS Config for frontend-backend separation.

  • Integrate with Vault/Config Server for secret management.



Summary

Spring Security provides end-to-end security for Spring Boot microservices:

  • Authentication → In-memory, DB, LDAP, OAuth2, JWT

  • Authorization → Role-based, permission-based, method-level

  • Filters → Secure every HTTP request before hitting controllers

  • Attack Protection → CSRF, XSS, Clickjacking, SSL, brute-force prevention

  • Microservices Features → OAuth2 Resource Server, JWT, API Gateway security, SSO

  • Integration → Works with Spring Boot auto-config, Spring Cloud, Kubernetes


👉 In short: Spring Security can secure users, APIs, services, and infrastructure in a microservices ecosystem with flexibility and up-to-date defenses.



Spring Security vs Alternatives for Microservices

Feature / Aspect

Spring Security

Apache Shiro

Micronaut Security

Quarkus Security (OIDC)

Jakarta EE Security

Integration

Deep integration with Spring Boot & Spring Cloud. Auto-config, filters, method-level security.

Works in any Java app, not tied to Spring.

Built for Micronaut (lightweight DI framework).

Native for Quarkus, strong Keycloak integration.

Standard for Jakarta EE / Java EE servers.

Authentication Methods

Rich options → In-memory, DB (JDBC/JPA), LDAP, OAuth2, OIDC, JWT, SAML.

Username/password, LDAP, custom realms. Limited OAuth2/JWT support.

Strong JWT, OAuth2, OIDC support out-of-the-box.

JWT, OAuth2, OIDC (Keycloak ecosystem).

Standard JAAS/JASPIC providers.

Authorization (Access Control)

Role-based, authority/permission-based, fine-grained method security (@PreAuthorize).

Role & permission-based, simpler than Spring.

Annotation-driven roles & permissions.

Role-based, JWT claims-based.

Role-based, declarative (XML/annotations).

Microservices Focus

Built-in support for JWT, OAuth2 Resource Server, API Gateway, SSO.

Designed mainly for monoliths, not microservices.

Lightweight, cloud-native microservices focus.

Optimized for Kubernetes/containers with Keycloak.

Works, but oriented to enterprise monoliths.

Defenses Against Attacks

CSRF, XSS, Clickjacking, Session Fixation, CORS, SSL enforcement.

Basic session & crypto security.

CORS, JWT integrity, OAuth2 protections.

CORS, JWT integrity, SSL/TLS enforcement.

Basic filters, depends on app server.

Ease of Use

Steep learning curve, but very flexible.

Simple and lightweight to start.

Easier than Spring Security, less boilerplate.

Requires Quarkus & Keycloak knowledge.

Boilerplate-heavy, server-dependent.

Community & Ecosystem

Huge ecosystem, official Spring support, enterprise-ready.

Active but smaller than Spring.

Growing but relatively small.

Backed by Red Hat, smaller than Spring.

Standard, but slower updates.

Performance (Startup & Memory)

Heavier (Spring Boot adds overhead).

Lightweight.

Fast startup, low memory footprint.

Very fast, GraalVM friendly.

Depends on server, not cloud-optimized.

Best Use Cases

Enterprise Spring Boot microservices, APIs, SSO, OAuth2, JWT, API Gateway.

Non-Spring Java apps, smaller scale apps.

Cloud-native microservices, serverless apps.

Kubernetes + Keycloak ecosystems.

Legacy Java EE apps on traditional servers.

Cons / Limitations

Complex setup, heavier for small apps.

Weak OAuth2/JWT support, smaller ecosystem.

Smaller adoption, limited enterprise adoption.

Best only with Quarkus stack, not portable.

More boilerplate, less cloud-native.


Key Highlights

  • Spring Security → Best for Spring Boot microservices; complete & enterprise-ready.
  • Apache Shiro → Best for non-Spring Java apps; simple but limited for modern microservices.
  • Micronaut Security → Good for lightweight, serverless, cloud-native apps.
  • Quarkus OIDC → Best if using Keycloak + Kubernetes.
  • Jakarta EE Security → Suitable for legacy Java EE apps; not optimized for modern cloud microservices.