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.
Key Points: • Spring Security manages authentication, authorization, session management, and security policies. • It supports multiple authentication mechanisms such as form login, database authentication, LDAP, OAuth2, JWT, and SSO. • It protects applications from common vulnerabilities like CSRF attacks, session fixation, and unauthorized access.
Steps to Implement Spring Security in 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
Load users from: • In-memory storage • Database • LDAP • OAuth Providers
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
Use annotations such as: • @PreAuthorize • @PostAuthorize • @Secured
Code Example:
@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();
}
}UserDetailsService Example:
@Service
public class CustomUserDetailsService
implements UserDetailsService {
@Override
public UserDetails
loadUserByUsername(
String username) {return User.builder() .username(username)
.password(
"$2a$...").roles("USER")
.build();
}
}Method-Level Security Example:
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(
Long userId) {
// business logic
}Common Security Features:
• Authentication • Authorization • Password Encryption • CSRF Protection • Session Management • Remember-Me Authentication • OAuth2 Login • JWT-Based Authentication • Single Sign-On (SSO)
Real-World Example:
In an e-commerce application:
• Customers can browse products. • Registered users can place orders. • Admin users can manage products and users.
Spring Security ensures that: • Only authenticated users place orders. • Only admins access admin APIs. • Passwords are stored securely using BCrypt.
Best Practices:
• Always encrypt passwords using BCrypt. • Follow the principle of least privilege. • Secure REST APIs using JWT or OAuth2. • Disable unnecessary endpoints. • Implement role-based access control.
Interview Tip: 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.