🎯 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
SecurityFilterChainbean 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
🔐 Real-world scenario
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.
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.
| Endpoint | Rule | No credentials | Wrong role | Correct role |
|---|---|---|---|---|
/api/hello | permitAll() | 200 | 200 | 200 |
/actuator/** | permitAll() | 200 | 200 | 200 |
/api/transfers/** | hasRole("AGENT") | 401 | 403 | 200 |
| anything else | authenticated() | 401 | 200 | 200 |
🔑 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.
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
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.
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.
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.
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.
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
SessionCreationPolicy.STATELESS do?BCryptPasswordEncoder do?.permitAll() and .authenticated()?Next: Mini Build — Task Management API →
⚠️ Common mistakes
{noop}password or NoOpPasswordEncoder stores plain text. Always use BCryptPasswordEncoder or Argon2 in any real environment.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./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
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 →