Posted in

30 Essential Spring Security Interview Questions and Answers for All Experience Levels

Prepare for Your Next Interview with These Spring Security Questions

Spring Security is the leading framework for securing Java applications. This comprehensive guide features 30 interview questions covering basic concepts to advanced scenarios, perfect for freshers, developers with 1-3 years experience, and professionals with 3-6+ years in the field.

Basic Spring Security Interview Questions

1. What is Spring Security?

Answer: Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de facto standard for securing Spring-based applications and provides comprehensive security services for J2EE-based enterprise software applications.[1][2][5]

2. What are the key features of Spring Security?

Answer: Key features include authentication and authorization support, protection against common attacks like CSRF and session fixation, seamless integration with Spring ecosystem, method-level security, and support for multiple authentication mechanisms.[2][5][6]

3. What is the difference between Authentication and Authorization in Spring Security?

Answer: Authentication verifies who you are (identity verification), while Authorization determines what you can do (access control). Authentication happens first, then authorization checks permissions.[1][3]

4. How do you configure Spring Security in a Spring Boot application?

Answer: Add the spring-boot-starter-security dependency and create a SecurityConfig class extending WebSecurityConfigurerAdapter or implementing SecurityFilterChain bean in newer versions.

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated());
        return http.build();
    }
}

[1]

5. What are the different types of authentication supported by Spring Security?

Answer: Spring Security supports form-based login, HTTP Basic authentication, HTTP Digest, X.509 certificate authentication, JWT, OAuth2, and custom authentication providers.[1][4]

6. What is the Security Filter Chain in Spring Security?

Answer: The Security Filter Chain is a series of filters that handle security concerns. Each filter has a specific responsibility like authentication, authorization, CSRF protection, etc. Filters execute in a specific order.[3]

7. Explain UserDetails and UserDetailsService interfaces.

Answer: UserDetails represents the principal details (username, password, authorities). UserDetailsService is responsible for retrieving UserDetails from a repository like database during authentication.[3]

8. What is PasswordEncoder and why is it important?

Answer: PasswordEncoder encodes passwords before storing them. Spring Security never stores plain text passwords. BCryptPasswordEncoder is commonly used as it applies salting automatically.[3][4]

9. How does password encoding work during authentication?

Answer: During login, Spring Security encodes the incoming password and compares it with the stored encoded password. If hashes match, authentication succeeds.[3]

10. What is CSRF and how does Spring Security protect against it?

Answer: CSRF (Cross-Site Request Forgery) tricks users into executing unwanted actions. Spring Security provides CSRF protection by generating tokens that must be included in forms and verified on submission.[1][2][3]

Intermediate Spring Security Interview Questions

11. How do you implement form-based authentication?

Answer: Configure HttpSecurity with formLogin():

http.formLogin(form -> form
    .loginPage("/login")
    .defaultSuccessUrl("/home")
    .permitAll());

[1]

12. How can you secure specific URL patterns?

Answer: Use authorizeHttpRequests() to define URL patterns and required roles:

auth.requestMatchers("/admin/**").hasRole("ADMIN")
    .requestMatchers("/user/**").hasRole("USER")
    .anyRequest().authenticated();

[1]

13. What is the difference between stateless and stateful authentication?

Answer: Stateful uses server-side sessions (traditional web apps). Stateless uses tokens like JWT (REST APIs, microservices) where server doesn’t maintain session state.[1]

14. How do you configure method-level security?

Answer: Enable with @EnableGlobalMethodSecurity(prePostEnabled = true) and use @PreAuthorize or @Secured annotations on methods.

@PreAuthorize("hasRole('ADMIN')")
public void adminMethod() {}

[1][4]

15. Explain @PreAuthorize vs @PostAuthorize annotations.

Answer: @PreAuthorize checks security before method execution. @PostAuthorize checks after execution, useful when authorization depends on method return value.[1][4]

16. How do you implement session management?

Answer: Configure session settings with sessionManagement():

http.sessionManagement(session -> session
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .maximumSessions(1));

[1]

17. What is the AuthenticationManager and its role?

Answer: AuthenticationManager is responsible for processing authentication requests. It delegates to AuthenticationProviders which contain the actual authentication logic.[3]

18. How do you handle exceptions in Spring Security?

Answer: Use exceptionHandling() to configure custom error handling:

http.exceptionHandling(exceptions -> exceptions
    .authenticationEntryPoint(unauthorizedHandler));

[1]

19. What is SecurityContext and how does it work?

Answer: SecurityContext holds the Authentication object for the current request. SecurityContextHolder stores it thread-locally for access throughout the request lifecycle.[3]

20. How do you create a custom AuthenticationProvider?

Answer: Implement AuthenticationProvider interface and override authenticate() method for custom authentication logic, then add to AuthenticationManager.[3]

Advanced Spring Security Interview Questions

21. How do you implement JWT authentication in Spring Security?

Answer: Create JWT token on successful login, validate token in a custom filter (JwtAuthenticationFilter) placed before UsernamePasswordAuthenticationFilter.[1][3]

22. At Atlassian, how would you secure REST APIs for Jira integrations using Spring Security?

Answer: Implement stateless JWT authentication with role-based access control and CORS configuration for cross-origin requests from Jira frontend.[1]

23. Explain role-based vs permission-based access control.

Answer: Role-based uses broad roles like ROLE_ADMIN. Permission-based uses granular permissions like READ_PRIVILEGE, WRITE_PRIVILEGE for fine-grained control.[4]

24. How do you configure CORS in Spring Security?

Answer: Use cors() in HttpSecurity:

http.cors(cors -> cors.configurationSource(corsConfig()));

Define CorsConfigurationSource bean allowing specific origins.[1]

25. What is the purpose of a custom security filter?

Answer: Custom filters extend AbstractAuthenticationProcessingFilter or OncePerRequestFilter for specific security concerns like custom token validation or audit logging.[1]

26. In a Paytm-like fintech scenario, how would you implement concurrent session control?

Answer: Configure maximumSessions(1) with SessionRegistry to prevent multiple simultaneous logins for financial security.[1]

27. How does Spring Security prevent common vulnerabilities like XSS?

Answer: Spring Security integrates with output encoding mechanisms and provides headers like X-XSS-Protection. Use @EnableWebSecurity’s default protections.[2][4]

28. Explain OAuth2 and OpenID Connect in Spring Security context.

Answer: OAuth2 handles authorization (delegation). OpenID Connect adds authentication layer on OAuth2 for identity verification using ID tokens.[4]

29. For Adobe’s creative cloud APIs, how would you implement rate limiting with Spring Security?

Answer: Create custom filter checking request rate against user/principal stored in SecurityContext, rejecting excessive requests with 429 status.[1]

30. How do you secure microservices architecture using Spring Security?

Answer: Use JWT propagation between services, API gateway with OAuth2 resource server config, mutual TLS for service-to-service communication, and distributed session management.[3]

## Key Takeaways for Interview Success

– **Freshers**: Master basic concepts (Q1-10) and simple configurations
– **1-3 Years**: Focus on intermediate implementation (Q11-20)
– **3-6+ Years**: Excel in advanced scenarios and real-world applications (Q21-30)

Practice these questions to demonstrate comprehensive Spring Security expertise across all experience levels.

Leave a Reply

Your email address will not be published. Required fields are marked *