Spring Security Interview Questions & Answers

1. What is Spring Security?

Answer: Spring Security is a powerful and customizable framework for authentication, authorization, and access control in Java applications. It integrates seamlessly with the Spring Framework to secure web applications, REST APIs, and method-level access.

2. What are the key features of Spring Security?

Answer:

  • Authentication (verifying user identity)
  • Authorization (controlling access to resources)
  • Protection against common attacks (CSRF, session fixation, clickjacking)
  • Integration with OAuth2 and JWT
  • Method-level security with annotations like @PreAuthorize and @Secured

3. How does Spring Security handle authentication?

Answer: Authentication is managed through AuthenticationManager and AuthenticationProvider. User credentials are validated, and upon success, an Authentication object is stored in the SecurityContextHolder.

4. What is the difference between authentication and authorization?

Answer:

  • Authentication: Confirms the identity of the user (e.g., login with username/password).
  • Authorization: Determines what actions or resources the authenticated user can access.

5. How do you secure REST APIs with Spring Security?

Answer:

  • Configure stateless authentication using JWT or OAuth2.
  • Use HttpSecurity to restrict endpoints (.authorizeHttpRequests()).
  • Apply role-based access with @PreAuthorize("hasRole('ADMIN')").
  • Enable CSRF protection for non-REST endpoints.

6. What is CSRF protection in Spring Security?

Answer: CSRF (Cross-Site Request Forgery) protection ensures that malicious sites cannot trick authenticated users into performing unintended actions. Spring Security enables CSRF tokens by default for state-changing requests.

7. How do you implement method-level security?

Answer:

  • Enable method security with @EnableGlobalMethodSecurity(prePostEnabled = true).
  • Use annotations like @PreAuthorize, @PostAuthorize, and @Secured to restrict access at the method level.

8. What is the role of UserDetailsService?

Answer: UserDetailsService loads user-specific data (username, password, roles) from a database or other source. It is a core interface used by Spring Security for authentication.

9. How does Spring Security integrate with OAuth2?

Answer: Spring Security provides built-in support for OAuth2 login and resource server functionality. It allows applications to authenticate users via external providers (Google, GitHub, etc.) and secure APIs with access tokens.

10. What are common authentication mechanisms supported?

Answer:

  • Form-based login
  • Basic authentication
  • Digest authentication
  • LDAP authentication
  • JWT/OAuth2 token-based authentication

Leave a Comment