Spring Security helps protect your app from bad users and keeps data safe. It makes sure only the right people can see or change things.
Why Spring Security matters in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Spring Boot
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); } }
This is a basic setup to require login for all pages.
@EnableWebSecurity turns on security features in your app.
Examples
Spring Boot
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin(); } }
Spring Boot
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated() .and() .httpBasic(); } }
Sample Program
This Spring Boot app uses Spring Security to require users to log in before accessing any page. It shows a simple login form automatically.
Spring Boot
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @Configuration @EnableWebSecurity class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin(); } }
Important Notes
Spring Security works behind the scenes to protect your app without much setup.
You can customize who can access what by changing the rules in the configuration.
It also helps protect against common attacks like CSRF and session fixation.
Summary
Spring Security keeps your app safe by controlling access.
It is easy to add login and protect pages with simple setup.
You can customize security rules to fit your app's needs.
Practice
1. Why is Spring Security important in a Spring Boot application?
easy
Solution
Step 1: Understand the role of Spring Security
Spring Security is designed to protect applications by managing authentication and authorization.Step 2: Compare options with Spring Security's purpose
Only It helps protect the app by controlling who can access what. correctly describes controlling access, which is the core of Spring Security.Final Answer:
It helps protect the app by controlling who can access what. -> Option AQuick Check:
Security = Access control [OK]
Hint: Spring Security controls access to keep apps safe [OK]
Common Mistakes:
- Confusing security with performance optimization
- Thinking it manages UI design
- Assuming it handles database connections
2. Which of the following is the correct way to enable Spring Security in a Spring Boot project?
easy
Solution
Step 1: Identify the dependency for Spring Security
The official way to add Spring Security is by includingspring-boot-starter-securityin your project.Step 2: Eliminate incorrect options
Options A, C, and D do not enable Spring Security properly; they relate to web, custom code, or database, not security starter.Final Answer:
Add the dependencyspring-boot-starter-securityto your build file. -> Option BQuick Check:
Security starter dependency = Add the dependencyspring-boot-starter-securityto your build file. [OK]
Hint: Add spring-boot-starter-security dependency to enable security [OK]
Common Mistakes:
- Adding unrelated dependencies
- Trying to implement security without starter
- Confusing web or data dependencies with security
3. Given this Spring Security configuration snippet, what will happen when a user tries to access
/admin without logging in?http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin").authenticated()
.anyRequest().permitAll()
)
.formLogin();medium
Solution
Step 1: Analyze the security rules for
The config requires authentication for/admin/adminand permits all other requests.Step 2: Understand form login behavior
Since.formLogin()is enabled, unauthenticated users are redirected to a login page automatically.Final Answer:
The user will be redirected to a login page before accessing/admin. -> Option DQuick Check:
Authenticated access + formLogin = redirect to login [OK]
Hint: Authenticated paths redirect to login page if not logged in [OK]
Common Mistakes:
- Assuming access without login
- Confusing 404 with access denial
- Thinking permission denied shows without login
4. Identify the error in this Spring Security configuration code:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.requestMatchers("/user").authenticated()
.anyRequest().permitAll();
return http.build();
}medium
Solution
Step 1: Check the usage of
In Spring Security 6+,authorizeHttpRequests()authorizeHttpRequests()requires a lambda to configure rules.Step 2: Identify missing lambda argument
The code callsauthorizeHttpRequests()without a lambda, causing a syntax error.Final Answer:
The methodauthorizeHttpRequests()requires a lambda argument. -> Option CQuick Check:
authorizeHttpRequests needs lambda = The methodauthorizeHttpRequests()requires a lambda argument. [OK]
Hint: authorizeHttpRequests needs lambda for rules in Spring Security 6+ [OK]
Common Mistakes:
- Omitting lambda argument for authorizeHttpRequests
- Confusing requestMatchers with antMatchers
- Incorrect method calls on HttpSecurity
5. You want to customize Spring Security to allow only users with role
ADMIN to access /admin, but allow everyone else to access /public. Which configuration snippet correctly achieves this?hard
Solution
Step 1: Check role-based access for
/adminhttp .authorizeHttpRequests(auth -> auth .requestMatchers("/admin").hasRole("ADMIN") .requestMatchers("/public").permitAll() .anyRequest().denyAll() ) .formLogin();useshasRole("ADMIN")which correctly restricts/adminto ADMIN users.Step 2: Verify public access and deny others
http .authorizeHttpRequests(auth -> auth .requestMatchers("/admin").hasRole("ADMIN") .requestMatchers("/public").permitAll() .anyRequest().denyAll() ) .formLogin();permits all to/publicand denies all other requests, matching the requirement.Final Answer:
http .authorizeHttpRequests(auth -> auth .requestMatchers("/admin").hasRole("ADMIN") .requestMatchers("/public").permitAll() .anyRequest().denyAll() ) .formLogin();-> Option AQuick Check:
hasRole ADMIN + permitAll public + deny others =http .authorizeHttpRequests(auth -> auth .requestMatchers("/admin").hasRole("ADMIN") .requestMatchers("/public").permitAll() .anyRequest().denyAll() ) .formLogin();[OK]
Hint: Use hasRole("ADMIN") for admin, permitAll for public [OK]
Common Mistakes:
- Swapping roles and permissions for paths
- Allowing public access to admin paths
- Using hasAuthority instead of hasRole without prefix
