Top 10 Spring Security Interview Questions for Spring Boot Developers
Spring Security is a powerful and flexible tool in the Spring framework, providing authentication, authorization, and protection against common security vulnerabilities. Its seamless integration with Spring Boot has made it the go-to solution for securing Java-based applications. For Spring Boot developers, expertise in this area is critical for building secure and production-ready systems—and for excelling during technical interviews.
This guide explores the Top 10 Spring Security Interview Questions for Spring Boot Developers, offering detailed answers, real-world examples, and insights to help you prepare effectively.
Table of Contents
- What is Spring Security and How Does It Integrate with Spring Boot?
- Default Security Behavior in Spring Boot
- Securing REST APIs with HTTP Basic and JWT
- Role-Based Access Control with @PreAuthorize
- Custom Login and Authentication Filters
- Stateless vs Stateful Authentication
- Password Encoding and Security Best Practices
- Using OAuth2 with Spring Boot
- CSRF Protection and When to Disable It
- Common Spring Security Configuration Mistakes
1. What is Spring Security and How Does It Integrate with Spring Boot?
Spring Security is the de facto standard for securing Spring-based applications. It provides a robust framework to handle authentication, authorization, and protection against security threats like CSRF, session fixation, and more.
Integration with Spring Boot:
Spring Boot simplifies the configuration of Spring Security through auto-configuration. When you add the Spring Security dependency to your project, Spring Boot automatically configures basic authentication with default settings.
Example:
Add Dependency inpom.xml
:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
Default Integration:
Spring Security auto-applies basic authentication to all endpoints when launched.
Further Reading:
2. Default Security Behavior in Spring Boot
When Spring Security is enabled in a Spring Boot application, its default setup includes:
- Denying access to all endpoints for unauthenticated users.
- Enabling
HTTP Basic
authentication by default. - A default login page for form-based authentication.
How to Customize:
To override these defaults, use a @Configuration
class and extend WebSecurityConfigurerAdapter
(deprecated in recent Spring versions, replaced with SecurityFilterChain
).
Default Security Example:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest() .authenticated() .and() .formLogin(); } }
Pro Tip: Familiarize yourself with the transition to SecurityFilterChain
in Spring Security 5.7+.
Spring Security Getting Started
3. Securing REST APIs with HTTP Basic and JWT
Securing REST APIs with Spring Security can involve multiple mechanisms, including HTTP Basic
or the more secure JWT
.
HTTP Basic Authentication:
Simple but less secure as the credentials are sent in every request.
@Configuration public class ApiSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests().anyRequest().authenticated() .and() .httpBasic(); } }
JWT Authentication:
JWT is a stateless and token-based solution for secure API interaction.
Steps to Add JWT Security:
- Generate JWT on login.
- Validate Token in each API request via filters.
Example Filter for JWT Validation:
public class JwtFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = request.getHeader("Authorization"); // Validate token... filterChain.doFilter(request, response); } }
Pro Tip: Use Bearer
tokens for secure API interactions.
4. Role-Based Access Control with @PreAuthorize
The @PreAuthorize
annotation enables method-level security by specifying access control rules.
Example with Roles:
@PreAuthorize("hasRole('ADMIN')") public String adminEndpoint() { return "Admin Content"; }
Pro Tip: Combine with @EnableGlobalMethodSecurity
for activation.
Explore Method Security in Spring
5. Custom Login and Authentication Filters
Spring Security allows customization of authentication mechanisms during the login process.
Custom Login:
@Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() .loginPage("/login") .permitAll(); }
Custom Filters:
Integrate filters like JWT token parsers to override default behavior.
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter { // Custom logic here }
Pro Tip: Authenticate users via filters for specific use cases like token validation.
6. Stateless vs Stateful Authentication
| Aspect | Stateless | Stateful |
|———————–|——————————————-|——————————————|
| Session | No server-side sessions. | Relies on server-side sessions. |
| Example | JWT tokens. | Form-based login in web apps. |
| Scalability | Highly scalable. | Limited by session storage capacity. |
Pro Tip: Default to stateless for REST APIs using JWT.
7. Password Encoding and Security Best Practices
Spring Security offers secure password storage through password encoders.
Example:
@Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }
Pro Tip: Avoid storing raw passwords and always hash user passwords with salts.
8. Using OAuth2 with Spring Boot
Spring Security integrates OAuth 2.0 for secure external authentication and API control.
Basic OAuth2 Setup:
@Configuration public class OAuthConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("client-id") .secret("client-secret") .authorizedGrantTypes("authorization_code") .scopes("read", "write"); } }
Learn more about Spring Security OAuth2
9. CSRF Protection and When to Disable It
CSRF (Cross-Site Request Forgery) protects against unauthorized state-changing actions.
Disable When Using APIs:
@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); }
Pro Tip: Keep CSRF enabled for traditional web applications but disable it for REST APIs.
10. Common Spring Security Configuration Mistakes
- Disabling CSRF without understanding implications.
- Hardcoding credentials in source code.
- Using outdated password encoding mechanisms.
- Failing to update JWT token expiration policies.
Pro Tip: Regularly review configurations for compliance and vulnerabilities.
FAQs
What’s the default password for Spring Security?
Spring Security generates a temporary password on startup (logged to the console).
How do I enable Spring Security?
Add the spring-boot-starter-security
dependency—auto-configuration will handle defaults.
Why is CSRF disabled for REST APIs?
Because REST APIs often use stateless authentication like JWTs, which don’t rely on cookies.
Summary
Mastering Spring Security’s features—from securing REST APIs with JWT to handling custom authentication filters—is crucial for Spring Boot developers. By understanding configuration best practices, default security behaviors, and advanced features like OAuth2 and role-based access control, you’ll be well-prepared for any technical challenge or interview.
Keep exploring to build even more secure and scalable applications!