Introduction to Spring Security


Introduction to Spring Security Interview with follow-up questions

1. What is Spring Security and why is it important?

Spring Security is the de-facto authentication and authorization framework for Spring applications. It's a chain of servlet filters that intercept requests to enforce security, plus a rich model for identity and access control. It protects against common threats out of the box: it secures endpoints, manages sessions, and defends against CSRF, session fixation, clickjacking, etc.

Core capabilities:

  • Authentication — verify identity via form login, HTTP Basic, OAuth2/OIDC, JWT, LDAP, SAML.
  • Authorization — URL- and method-level access control (roles/authorities), @PreAuthorize.
  • Protections — CSRF tokens, security headers, password encoding (BCrypt/Argon2), session management.
  • Deep integration — with Spring MVC/WebFlux, Boot auto-configuration, and method security.

Why it matters: security is hard and easy to get wrong; Spring Security gives you vetted, configurable defaults so you don't hand-roll auth. The 2026 framing interviewers want: configuration is now component-based — you define a SecurityFilterChain bean with the lambda DSL (the old WebSecurityConfigurerAdapter was removed in Spring Security 6), it runs on Jakarta (jakarta.servlet) under Boot 3+, and it has first-class OAuth2 resource server / login support for modern token-based APIs.

↑ Back to top

Follow-up 1

Can you explain the core components of Spring Security?

The core components of Spring Security include:

  1. Authentication: This component handles the process of verifying the identity of a user.

  2. Authorization: This component controls access to resources based on the authenticated user's roles and permissions.

  3. UserDetailsService: This component is responsible for loading user-specific data during the authentication process.

  4. SecurityContextHolder: This component holds the security context of the current user.

  5. AccessDecisionManager: This component determines whether an authenticated user has the necessary permissions to access a specific resource.

  6. FilterChainProxy: This component manages the chain of security filters that process incoming requests.

These components work together to provide a comprehensive security solution for your application.

Follow-up 2

How does Spring Security handle authentication and authorization?

Spring Security provides various mechanisms for authentication and authorization:

  1. Authentication: Spring Security supports multiple authentication mechanisms such as form-based authentication, HTTP Basic authentication, and OAuth. It also allows for custom authentication providers.

  2. Authorization: Spring Security uses a combination of access control rules, roles, and permissions to control access to resources. It provides annotations and configuration options to define fine-grained access control rules.

Overall, Spring Security makes it easy to implement robust authentication and authorization mechanisms in your application.

Follow-up 3

What are some common use cases for Spring Security?

Some common use cases for Spring Security include:

  1. Securing web applications: Spring Security can be used to secure web applications by adding authentication and authorization mechanisms.

  2. Securing RESTful APIs: Spring Security can be used to secure RESTful APIs by implementing token-based authentication and authorization mechanisms.

  3. Single sign-on (SSO): Spring Security can be used to implement SSO across multiple applications by integrating with identity providers such as OAuth or SAML.

  4. Role-based access control: Spring Security can be used to implement role-based access control, where different users have different levels of access based on their roles.

These are just a few examples, but Spring Security is highly flexible and can be adapted to various security requirements.

Follow-up 4

How does Spring Security integrate with other Spring projects?

Spring Security integrates seamlessly with other Spring projects. Some of the key integrations include:

  1. Spring Boot: Spring Security is tightly integrated with Spring Boot, making it easy to configure security settings using properties and annotations.

  2. Spring MVC: Spring Security can be used with Spring MVC to secure web applications and RESTful APIs.

  3. Spring Data: Spring Security can be used with Spring Data to secure access to database resources.

  4. Spring Cloud: Spring Security can be used with Spring Cloud to secure microservices and implement distributed security.

These integrations make it easy to build secure and scalable applications using the Spring ecosystem.

2. How does Spring Security handle authentication?

Authentication is verifying who the user is. Spring Security runs it through a well-defined chain of collaborators:

  1. An authentication filter (e.g. UsernamePasswordAuthenticationFilter, or the Bearer-token filter for APIs) extracts credentials from the request and builds an Authentication token.
  2. The AuthenticationManager (usually ProviderManager) delegates to one or more AuthenticationProviders.
  3. A provider (e.g. DaoAuthenticationProvider) loads the user via UserDetailsService and checks the password with a PasswordEncoder (BCrypt/Argon2).
  4. On success, a fully populated Authentication (principal + authorities) is stored in the SecurityContext (and typically the session, or carried by a token for stateless APIs).
@Bean
SecurityFilterChain chain(HttpSecurity http) throws Exception {
  http.authorizeHttpRequests(a -> a.anyRequest().authenticated())
      .formLogin(withDefaults());
  return http.build();
}
@Bean PasswordEncoder encoder() { return new BCryptPasswordEncoder(); }

Mechanisms supported: form login, HTTP Basic, OAuth2/OIDC login, JWT/opaque-token resource server, LDAP, SAML. Points interviewers reward: never store plaintext passwords (use a PasswordEncoder), and for stateless REST APIs prefer token-based auth (JWT via oauth2ResourceServer) over server sessions. Configure all of this via a SecurityFilterChain bean (the WebSecurityConfigurerAdapter of old is gone in Security 6).

↑ Back to top

Follow-up 1

What is the role of AuthenticationManager in Spring Security?

The AuthenticationManager is a core component of Spring Security that is responsible for authenticating the user. It delegates the authentication process to one or more AuthenticationProviders, which are responsible for validating the user's credentials and returning an Authentication object. The AuthenticationManager then performs additional checks, such as account locking or password expiration, and returns a fully authenticated Authentication object.

Follow-up 2

Can you explain the process of authentication in Spring Security?

The process of authentication in Spring Security involves the following steps:

  1. The user submits their credentials (e.g., username and password) to the application.
  2. The application receives the credentials and passes them to the AuthenticationManager.
  3. The AuthenticationManager delegates the authentication process to one or more AuthenticationProviders.
  4. Each AuthenticationProvider validates the user's credentials and returns an Authentication object.
  5. The AuthenticationManager performs additional checks, such as account locking or password expiration.
  6. The AuthenticationManager returns a fully authenticated Authentication object to the application.

Follow-up 3

What is an Authentication object in Spring Security?

In Spring Security, an Authentication object represents the user's credentials and other details during the authentication process. It contains information such as the user's principal (e.g., username), credentials (e.g., password or token), and authorities (e.g., roles or permissions). The Authentication object is created by an AuthenticationProvider and is used by Spring Security to determine the user's authentication status and access control permissions.

Follow-up 4

How can you customize the authentication process in Spring Security?

Spring Security provides various ways to customize the authentication process:

  1. Implementing a custom AuthenticationProvider: You can create a custom AuthenticationProvider to handle authentication using your own logic or integrate with external authentication systems.

  2. Configuring custom authentication filters: You can configure custom authentication filters to intercept and modify the authentication process.

  3. Using custom authentication success and failure handlers: You can define custom success and failure handlers to perform additional actions after successful or failed authentication.

  4. Implementing custom UserDetailsService: You can implement a custom UserDetailsService to load user details from a custom data source, such as a database or LDAP directory.

These are just a few examples of how you can customize the authentication process in Spring Security. The framework provides a wide range of extension points and configuration options to meet various authentication requirements.

3. How does Spring Security handle authorization?

Authorization decides what an authenticated user may do — it runs after authentication, checking the principal's granted authorities/roles against access rules. Spring Security enforces it at two levels:

Request (URL) level — in the SecurityFilterChain:

http.authorizeHttpRequests(auth -> auth
    .requestMatchers("/public/**").permitAll()
    .requestMatchers("/admin/**").hasRole("ADMIN")
    .anyRequest().authenticated());

Method level — enable with @EnableMethodSecurity and annotate:

@PreAuthorize("hasRole('ADMIN') or #id == authentication.name")
public User get(String id) { ... }

Concepts interviewers expect: the difference between roles (hasRole('ADMIN') → authority ROLE_ADMIN) and authorities/permissions (hasAuthority('user:read')); RBAC vs ABAC (SpEL expressions for attribute checks); and @PreAuthorize/@PostAuthorize/@PreFilter/@PostFilter. A failed check yields 403 Forbidden (vs 401 for missing authentication).

The 2026 notes: use the modern authorizeHttpRequests (the old authorizeRequests/antMatchers are deprecated/removed) and @EnableMethodSecurity (which replaced @EnableGlobalMethodSecurity). And the cardinal rule — broken access control is a top OWASP risk, so authorize on the server for every protected operation, never trust the client.

↑ Back to top

Follow-up 1

What is the role of AccessDecisionManager in Spring Security?

The AccessDecisionManager is responsible for making the final decision on whether a user is granted access to a resource or not. It takes into account the user's authentication information, the resource being accessed, and the user's roles and permissions. The AccessDecisionManager uses a set of AccessDecisionVoters to help make the decision.

Follow-up 2

Can you explain the process of authorization in Spring Security?

The process of authorization in Spring Security involves the following steps:

  1. Authentication: The user provides their credentials (username and password) to authenticate themselves.
  2. Access Control: Spring Security checks the user's roles and permissions to determine if they are authorized to access the requested resource.
  3. AccessDecisionManager: The AccessDecisionManager makes the final decision on whether the user is granted access or not.
  4. AccessDeniedHandler: If access is denied, the AccessDeniedHandler handles the situation and returns an appropriate response.

Follow-up 3

What is a GrantedAuthority in Spring Security?

In Spring Security, a GrantedAuthority represents a permission or role that a user possesses. It is used to define the user's access rights. The GrantedAuthority interface provides a single method, getAuthority(), which returns a String representing the authority.

Follow-up 4

How can you customize the authorization process in Spring Security?

You can customize the authorization process in Spring Security by implementing your own AccessDecisionManager and AccessDecisionVoters. The AccessDecisionManager is responsible for making the final decision on access, and the AccessDecisionVoters are responsible for providing input to the decision-making process. By implementing these interfaces, you can define your own logic for determining access based on your application's requirements.

4. What is the security context in Spring Security?

The SecurityContext holds the security information for the current request/thread — chiefly the Authentication object, which contains the principal (the authenticated user, often a UserDetails), the credentials, and the granted authorities (roles/permissions). It's how any layer of the app knows who is calling and what they can do.

It's accessed via the SecurityContextHolder:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
var authorities = auth.getAuthorities();

Key details interviewers probe: by default the context is thread-bound via a ThreadLocal (MODE_THREADLOCAL), so it's available throughout a request but doesn't propagate to new threads automatically — for async/@Async work you need DelegatingSecurityContextRunnable/MODE_INHERITABLETHREADLOCAL or the context-propagation support. Between requests it's persisted by the SecurityContextRepository (the HttpSession for stateful apps; nothing for stateless token APIs, where the token re-establishes it each request).

In practice you rarely touch SecurityContextHolder directly — you inject the current user with @AuthenticationPrincipal or a method parameter of type Authentication/Principal. A current note: Spring Security 6 changed the default context-saving behavior (explicit save via SecurityContextRepository), which matters for custom/stateless flows.

↑ Back to top

Follow-up 1

What is the role of SecurityContextHolder in Spring Security?

The SecurityContextHolder is a class in Spring Security that provides access to the security context. It is used to store and retrieve the security context for the current thread. The SecurityContextHolder uses a ThreadLocal to store the security context, ensuring that each thread has its own security context.

Follow-up 2

How is the security context maintained in Spring Security?

The security context is maintained in Spring Security by using the SecurityContextHolder. When a user is authenticated, the security context is created and stored in the SecurityContextHolder. Subsequent requests from the same user can then access the security context to retrieve the user's details and authorities. The security context is cleared when the user logs out or the session expires.

Follow-up 3

What is a SecurityContext object in Spring Security?

A SecurityContext object in Spring Security represents the security context for a user. It contains the user's principal (username or user object) and their granted authorities (roles or permissions). The SecurityContext object is stored in the SecurityContextHolder and can be accessed throughout the application to retrieve the user's security details.

Follow-up 4

How can you customize the security context in Spring Security?

You can customize the security context in Spring Security by implementing a custom AuthenticationProvider. The AuthenticationProvider is responsible for authenticating a user and creating an Authentication object, which contains the user's principal and authorities. You can also customize the security context by implementing a custom UserDetailsService, which is responsible for loading the user's details (username, password, and authorities) from a data source. Additionally, you can use Spring Security's built-in mechanisms for customizing the security context, such as configuring different authentication mechanisms (e.g., form-based login, OAuth, etc.) and defining access control rules (e.g., URL-based security).

5. How does Spring Security handle CSRF protection?

CSRF (Cross-Site Request Forgery) tricks an authenticated user's browser into making an unwanted state-changing request. Spring Security defends against it with the synchronizer token pattern: it issues a per-session CSRF token that must accompany every state-changing request (POST/PUT/PATCH/DELETE); requests without a valid token are rejected with 403.

http.csrf(csrf -> csrf
    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()));

Key points interviewers want:

  • CSRF protection is on by default, and applies only to state-changing methods (GET/HEAD are exempt).
  • For server-rendered forms, the token is injected automatically (e.g. Thymeleaf adds a hidden field); for SPAs/JS, expose it via a cookie (CookieCsrfTokenRepository) and echo it in a header (X-XSRF-TOKEN).
  • Stateless, token-based REST APIs (JWT in an Authorization header) are typically not vulnerable to CSRF, so it's common to disable CSRF there — but only because auth isn't carried in an ambient cookie. If you use cookie-based sessions, keep CSRF enabled.

A 2026 nuance: Spring Security 6 changed CSRF token loading (deferred/BREACH-protected tokens via CsrfTokenRequestAttributeHandler), which occasionally requires explicit configuration for SPAs — worth mentioning as a current gotcha.

↑ Back to top

Follow-up 1

What is CSRF and why is it a threat?

CSRF (Cross-Site Request Forgery) is a type of attack where an attacker tricks a user into performing an unwanted action on a website in which the user is authenticated. It is a threat because it can lead to unauthorized actions being performed on behalf of the user, such as changing passwords, making purchases, or deleting data.

Follow-up 2

How does Spring Security's CSRF protection work?

Spring Security's CSRF protection works by generating a CSRF token for each user session. This token is included in all HTML forms and AJAX requests as a hidden field or header. When a request is made, Spring Security checks if the CSRF token matches the one stored in the user's session. If the tokens match, the request is considered valid and processed. If the tokens do not match, the request is rejected as a potential CSRF attack.

Follow-up 3

How can you customize the CSRF protection in Spring Security?

You can customize the CSRF protection in Spring Security by configuring the CSRF token generation and validation process. Some of the customization options include:

  • Changing the token storage strategy (e.g., using cookies instead of session)
  • Excluding certain URLs from CSRF protection
  • Customizing the token generation and validation logic

These customizations can be done by extending the CsrfTokenRepository interface and configuring it in the Spring Security configuration.

Follow-up 4

What are some common use cases for CSRF protection in Spring Security?

Some common use cases for CSRF protection in Spring Security include:

  • Protecting user authentication and authorization actions, such as login and logout
  • Protecting sensitive operations, such as changing passwords or making financial transactions
  • Protecting data modification actions, such as submitting forms or updating user profiles

By enabling CSRF protection, you can ensure that these actions can only be performed by legitimate users and not by malicious attackers.

Live mock interview

Mock interview: Introduction to Spring Security

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.