Spring Security is a powerful framework used to secure Spring Boot applications by handling authentication (verifying user identity) and authorization (controlling access to resources). It provides built-in protection against common security threats and integrates seamlessly with Spring Boot.
1. Add Spring Security Dependency
Include the Spring Security starter dependency in the project.
2. Configure Security Rules
Create a security configuration class to define which endpoints are public and which require authentication.
3. Configure User Authentication
4. Encode Passwords
Use BCryptPasswordEncoder to securely store passwords.
5. Secure APIs and Endpoints
Apply role-based access control using annotations and security configuration.
6. Enable Method-Level Security
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain
securityFilterChain(
HttpSecurity http)
throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(
"/public/**")
.permitAll()
.requestMatchers(
"/admin/**")
.hasRole("ADMIN")
.anyRequest()
.authenticated())
.formLogin();
return http.build();
}
@Bean
public PasswordEncoder
passwordEncoder() {
return new BCryptPasswordEncoder();
}
}@Service
public class CustomUserDetailsService
implements UserDetailsService {
@Override
public UserDetails
loadUserByUsername(
String username) {
return User.builder()
.username(username)
.password(
"$2a$...")
.roles("USER")
.build();
}
}@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(
Long userId) {
// business logic
}A concise interview answer is: Spring Security is implemented in Spring Boot by adding the Spring Security dependency, configuring a SecurityFilterChain, defining authentication using UserDetailsService, securing passwords with BCryptPasswordEncoder, and applying authorization rules using roles and annotations such as @PreAuthorize. It provides authentication, authorization, and protection against common security vulnerabilities.
Last updated: 11 November 2026
Previous question: What is the Spring Boot CLI, and how do you run a Spring Boot project with it?
Next question: Explain the difference between cache eviction and cache expiration.