🎯 What you will learn

Spring Security is a powerful, highly customisable authentication and access-control framework. It plugs into the Spring Boot auto-configuration system with a single bean — SecurityFilterChain — and intercepts every HTTP request before it reaches your controllers. By the end of this lesson you will understand:

  • How to configure a SecurityFilterChain bean with the HttpSecurity DSL
  • HTTP Basic Auth — sending credentials on every request
  • Stateless session policy — no HttpSession, pure REST
  • Role-based access control with hasRole, hasAuthority, permitAll
  • BCryptPasswordEncoder — salted, slow hashing that resists brute-force
  • InMemoryUserDetailsManager for demo/test users
  • The 401 vs 403 distinction
💼 Interview reality: "Walk me through a Spring Security filter chain" and "what is the difference between 401 and 403?" appear in virtually every Java backend security round. Understanding the filter chain order and BCrypt's intentional slowness separates mid-level from senior candidates.

🔐 Real-world scenario

🔐
NairaSwift · Lagos, Nigeria
Lock down the transfers API

Samuel's transfer endpoints are open to anyone on the internet. He adds Spring Security: public endpoints (/hello, /ping, /actuator) stay open; /api/transfers/** requires the AGENT role; passwords are BCrypt-hashed in memory. A single SecurityFilterChain bean configures it all.

🛡️ SecurityConfig — the filter chain bean

All security rules live in one SecurityFilterChain bean. The HttpSecurity DSL lets you chain rules fluently: disable CSRF for stateless APIs, set session policy, define URL matchers, and choose the auth mechanism.

curl -s -o /dev/null -w "HTTP %{http_code}" http://localhost:8765/api/transfers
SecurityConfig.javaLesson 25 · SecurityFilterChain + InMemoryUserDetailsManager
verified output — unauthenticated request
HTTP 401

Why disable CSRF? CSRF tokens protect browser-based form submissions that rely on session cookies. Stateless REST APIs authenticate on every request via headers (Basic, Bearer), so there is no session to hijack — CSRF protection adds overhead with no benefit.

🚦 Public vs protected endpoints

Spring Security evaluates matchers top-to-bottom. The first matching rule wins. Public endpoints declared with permitAll() never reach the authentication check — they pass straight to the controller. Protected endpoints without valid credentials receive a 401 Unauthorized response with a WWW-Authenticate: Basic header.

curl -s -o /dev/null -w "HTTP %{http_code}" http://localhost:8765/api/hello
EndpointAccess.javaLesson 25 · public vs protected curl tests
verified output — all three curl tests
HTTP 200 HTTP 401 HTTP 200
EndpointRuleNo credentialsWrong roleCorrect role
/api/hellopermitAll()200200200
/actuator/**permitAll()200200200
/api/transfers/**hasRole("AGENT")401403200
anything elseauthenticated()401200200

🔑 Role-based access + BCrypt

BCrypt is intentionally slow. The cost factor (default 10) means each hash takes ~100 ms to compute — acceptable for a single login but devastating for an attacker trying millions of guesses per second. Each call to encode() embeds a unique random salt, so two identical passwords produce different hashes.

curl -s -u samuel:pass123 -X DELETE -o /dev/null -w "HTTP %{http_code}" http://localhost:8765/api/transfers/1001
BCryptDemo.javaLesson 25 · hasRole, hasAuthority, BCryptPasswordEncoder
verified output — authenticated DELETE
HTTP 204

hasRole vs hasAuthority: hasRole("AGENT") automatically prepends ROLE_ to the string — it looks for ROLE_AGENT. hasAuthority("ROLE_AGENT") uses the exact string. Never write hasRole("ROLE_AGENT") — it looks for ROLE_ROLE_AGENT and will always deny access.

🎤 Interview Q&A

EasyWhat is the difference between HTTP Basic and Bearer token (JWT) authentication?
+

HTTP Basic sends username:password Base64-encoded on every request — simple but the password travels on the wire. Bearer tokens (JWT) are signed tokens issued after login; subsequent requests send the token, not the password. Use JWT for production APIs.

EasyWhat is the difference between 401 and 403?
+

401 means "I don't know who you are — provide credentials." 403 means "I know who you are but you're not allowed." Spring Security returns 401 for missing/invalid credentials and 403 for insufficient authority.

MediumHow does the SecurityFilterChain work?
+

Spring Security inserts a chain of servlet filters before the DispatcherServlet. Each filter handles one concern (CSRF, authentication, authorisation). SecurityFilterChain lets you configure which filters run and in what order via the HttpSecurity DSL.

MediumHow would you replace in-memory users with a database?
+

Implement UserDetailsService and override loadUserByUsername(String username) to query the database. Return a UserDetails object built from the DB row. Spring Security calls this method on every authentication attempt.

HardHow does Spring Security's filter chain integrate with the Servlet container?
+

Spring Boot registers a DelegatingFilterProxy named springSecurityFilterChain as a servlet filter. This proxy looks up the FilterChainProxy bean from the ApplicationContext on first request. FilterChainProxy evaluates each SecurityFilterChain's requestMatcher in order and delegates to the first matching chain. This design allows multiple independent security configurations (e.g., one for /api/**, one for /admin/**).

📝 Quiz — 5 questions

Question 1 of 5
What does SessionCreationPolicy.STATELESS do?
Question 2 of 5
What HTTP status does Spring Security return for unauthenticated requests?
Question 3 of 5
What does BCryptPasswordEncoder do?
Question 4 of 5
What is the difference between .permitAll() and .authenticated()?
Question 5 of 5
What annotation enables Spring Security's web configuration?
0
/ 5
Quiz complete!

Next: Mini Build — Task Management API →

⚠️ Common mistakes

Disabling CSRF for browser-based apps
CSRF protection is essential for apps that use session cookies (browser-based MVC apps). Only disable it for stateless REST APIs that use tokens/Basic auth.
Using NoOpPasswordEncoder in production
{noop}password or NoOpPasswordEncoder stores plain text. Always use BCryptPasswordEncoder or Argon2 in any real environment.
Confusing hasRole and hasAuthority
hasRole("AGENT") automatically prepends ROLE_. hasAuthority("ROLE_AGENT") uses the exact string. Using hasRole("ROLE_AGENT") looks for ROLE_ROLE_AGENT and will always deny.
Forgetting to expose actuator endpoints
After adding Spring Security, /actuator/health returns 401 by default. Always explicitly .permitAll() actuator health endpoints needed by load balancers.

✅ Key takeaways

  • SecurityFilterChain bean = the single source of truth for all security rules
  • STATELESS sessions + HTTP Basic = simple auth for internal/demo REST APIs
  • BCryptPasswordEncoder: slow + salted = resistant to brute-force and rainbow tables
  • 401 = unauthenticated; 403 = unauthorised (wrong role)
  • Replace InMemoryUserDetailsManager with a DB-backed UserDetailsService for production
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

From secured APIs to a full Spring Boot service

Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses →