Top Interview Questions for Spring Security in 2023 - IQCode

Overview of Spring Security

With the increasing accessibility of web applications on the internet, they are becoming more susceptible to security threats. Therefore, it is essential to maintain the security of these web applications. Spring Security is a part of the Spring Framework, which is responsible for securing Java applications from security threats.

Spring Security is a robust access-control framework for Java EE based enterprise applications that provides authentication and authorization features. Its servlet filters allow the application to enable authentication and authorization functionality. Its main function is to authenticate and authorize incoming requests for accessing any resource.

What is Spring Security?

Spring security is one of the most powerful and customizable access-control frameworks that provides several security features, such as authentication, authorization, etc., for enterprise applications. Its primary responsibility is to control access to an application by restricting unauthorized access to its resources. Spring Security provides an additional level of security for java applications at the application level.

Spring Security Interview Questions for Freshers

Q1: What are the essential features of Spring Security?

The key features of Spring Security are:

  • Authentication and Authorization
  • Support for various security models such as HTTP basic authentication, form-based authentication, and Single Sign-On (SSO) authentication.
  • Flexible and powerful API to configure the security aspects of an application.
  • Easy integration with other security tools and frameworks.
  • Integration with Spring framework components like Spring Web MVC, Spring Data, etc.
  • LDAP, OpenID, SAML, and OAuth integration.
  • Cross-site request forgery (CSRF) protection and session management.

Understanding Spring Security Authentication and Authorization

Spring Security is a powerful and highly customizable security framework for Java applications. It provides features such as authentication, authorization, input validation, and session management to secure web and non-web applications.

Authentication is the process of verifying the identity of a user by checking their credentials, such as a username and password. Spring Security provides different authentication mechanisms, including basic authentication, form-based authentication, and OAuth.

Authorization is the process of granting or denying access to specific resources or features based on a user's identity and their roles and permissions. Spring Security provides role-based and permission-based authorization mechanisms to control access to secured resources.

By using Spring Security, developers can easily add security features to their applications, making them more robust and reliable.


Basic authentication is a mechanism used by clients to authenticate themselves with a server using a username and password. The client sends a request to the server with the Authorization header containing the word 'Basic' followed by a space and the Base64-encoded string of the username and password. The server decodes the information and checks if the username and password are valid and authorized to access the requested resource.

Digest Authentication Explained

Digest Authentication is a method used for secure communication between a client and a server. It is a challenge-response protocol that provides an added layer of security over basic authentication. Here, the server sends a message (known as challenge) to the client, which the client then signs using a hash function and sends back to the server. The server then verifies the response to authenticate the client. This method is widely used for authentication in web applications that require enhanced security.

Explaining Session Management in Spring Security

Session management in Spring Security involves the management of user session information and authentication credentials. This includes processes such as session timeout, session fixation protection, and invalidation of sessions upon logout. Proper session management helps ensure the security of user data and prevent unauthorized access. Spring Security provides various session management strategies that can be customized to meet the specific requirements of different applications.

Understanding SecurityContext and SecurityContextHolder in Spring Security

In Spring Security, the SecurityContext represents the security-related state that is specific to a particular thread of execution. It contains information such as the currently authenticated user, any granted authorities or roles, and other security-related details.

The SecurityContextHolder is a class that provides a convenient way to retrieve the SecurityContext associated with the current thread of execution. It uses a ThreadLocal to store the SecurityContext, which ensures that each thread of execution has its own unique SecurityContext.

The SecurityContextHolder also provides methods to manipulate the SecurityContext. For example, you can set a new SecurityContext by calling the setContext() method, or you can clear the current SecurityContext by calling the clearContext() method.

Overall, understanding the SecurityContext and SecurityContextHolder is crucial for implementing secure authentication and authorization in your Spring-based applications.

Explanation of Spring Security OAuth2

Spring Security OAuth2 is a framework used for securing the APIs and applications using OAuth2. It provides a set of classes and filters which can be used to add OAuth2 authentication and authorization capabilities to your application. OAuth2 is an authorization protocol that allows secure token-based authentication and authorisation between a client and a server.

OAuth2 provides a way to delegate access to resources that are held by one application and owned by another, which is a common use case in distributed systems. Spring Security OAuth2 supports multiple grant types such as authorization code, password, client credential, and implicit. These grants help to obtain an access token that is then used to access protected resources.

Spring Security OAuth2 uses the concept of a resource server, which is responsible for protecting resources by validating access tokens against the authorization server. It also provides a mechanism for obtaining authorization from users to access their protected resources.

Overall, Spring Security OAuth2 helps to secure your applications using a well-established authorization protocol, OAuth2, and provides a flexible and powerful way to implement authentication and authorization in your application.

Explanation of OAuth2 Authorization Code Grant Type

The OAuth2 Authorization Code Grant Type is a type of OAuth2 authentication protocol used to grant access to resources of a user or application by a client application. This process involves the user's explicit consent to the client application's access request. The client application must authenticate to the authorization server using its client ID and client secret.

Once authenticated, the client application will request authorization for a specific resource from the user. This request is sent as a redirect to the authorization server, which will authenticate the user and ask for their consent to grant access to the client application.

If the user consents, the authorization server will issue an authorization code to the client application, which can be exchanged for an access token through a separate request. The access token is then used to access the requested resource on behalf of the user.

The Authorization Code Grant Type is considered a secure form of authentication because the client application never directly accesses the user's credentials, and the user has complete control over access to their resources.

Understanding Method Security and Its Significance

Method security refers to the process of securing individual methods of an application by restricting their access to unauthorized users. It is an essential aspect of application security and helps to prevent malicious attacks and unauthorized access to sensitive data.

Method security is necessary because not all users may have the same level of privileges and access to an application. Some users may have restricted access, while others may have elevated privileges. By implementing method security, developers can ensure that each user can only access the specific methods that they are authorized to use.

Method security is typically implemented by using security annotations or configuration files that restrict access to specific methods. These restrictions can be based on user roles, permissions, or other custom criteria as per the application's requirements.

Overall, method security is a critical aspect of application security and should be implemented to ensure the confidentiality, integrity, and availability of sensitive data within an application.

// Example of using security annotation to restrict access to methods

Understanding Hashing in Spring Security

Hashing is a process of transforming plain text passwords into obfuscated values before storing them in a database. This is done to ensure that if a database is compromised, the original passwords cannot be easily obtained.

In Spring Security, hashing is implemented using password encoders. These encoders take a raw password and convert it into a hashed value. Spring Security supports various hashing algorithms such as bcrypt, SHA-256, and MD5.

To use a password encoder in your Spring Security application, you need to first configure it in your SecurityConfig class. Here's an example of how to configure a BCryptPasswordEncoder:

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    protected void configure(HttpSecurity http) throws Exception {

In the above example, we have configured a BCryptPasswordEncoder and used it to encode the password "password" for the user "user". This encoded password will be stored in the in-memory authentication database.

By using a password encoder in your Spring Security application, you can ensure that user passwords are stored securely and that your application is resistant to password-related attacks.

Explanation of Salting and its Usage

Salting involves adding a randomly generated string, called a salt, to a password before hashing it. This process adds an extra layer of security to the password because it makes it much more difficult for attackers to crack passwords using techniques like dictionary attacks or rainbow table attacks.

The salt is typically stored in the database alongside the hashed password. When a user attempts to log in, the server retrieves the salt and uses it to generate a hash of the password that the user provided. If the hash matches the stored hash in the database, the user is authenticated.

Salting is particularly helpful in scenarios where many users have the same password, as attackers can't just store a single hash of the password and use it to gain access to multiple accounts. By using a different salt for each user, the attacker would need to generate a separate rainbow table for each user, significantly increasing the complexity of the attack.

In summary, salting is an essential technique for enhancing password security and protecting user accounts from unauthorized access.

Purpose of PasswordEncoder

PasswordEncoder is an interface in Spring Security that is responsible for encoding the user's password before storing it in the database. It can also be used for matching the password entered by the user during login with the encoded password in the database. This helps in ensuring the security of the user's password and sensitive information.

// Example usage of PasswordEncoder
 private PasswordEncoder passwordEncoder;
 String encodedPassword = passwordEncoder.encode("password"); // Encoding the raw password
 boolean isPasswordMatched = passwordEncoder.matches("password", encodedPassword); // Matching raw password with encoded password

H3. Explanation of AbstractSecurityInterceptor in Spring Security

The AbstractSecurityInterceptor is a class in the Spring Security framework that provides a core security functionality for intercepting method calls and ensuring that the caller has appropriate permission to invoke the method. It is an important part of Spring Security's architecture and is used extensively in many security modules of the framework.

The main purpose of AbstractSecurityInterceptor is to enforce authorization decisions on applications by verifying that the currently authenticated user has the required role or permission to execute a specific method. It provides a range of methods, including pre-invocation checks, post-invocation checks, and voting methods to evaluate the access decision.

In addition to providing core security functions, AbstractSecurityInterceptor is also a base class for several other security interceptors in Spring Security. These include MethodSecurityInterceptor, which provides fine-grained access control to individual method calls, and FilterInvocationInterceptor, which provides pre- and post-processing for incoming HTTP requests.

AbstractSecurityInterceptor is highly configurable and can be customized to meet the specific security requirements of an application. Overall, it plays a vital role in maintaining the security of Spring applications by allowing deployment of user-based authentication and providing easy integration with third-party security systems.

Is security a cross-cutting concern?

Security can be considered a cross-cutting concern as it affects multiple aspects of software development and deployment. It's not just a matter of implementing a set of security features, but also ensuring that security is integrated into all aspects of the software development lifecycle, from requirement gathering to testing and deployment.

// Sample code demonstrating how security can be implemented as a cross-cutting concern

public class UserController {

    private final SecurityService securityService;

    public UserController(SecurityService securityService) {
        this.securityService = securityService;

    public void createUser(User user) {
        // perform other operations related to creating a user

    public User getUser(int id) {
        // perform other operations related to getting user details

public interface SecurityService {
    void validateUser(User user);
    void authorizeUser(int id);

In the code above, the


class depends on the


interface for performing security-related operations such as validating and authorizing users. This allows security to be implemented uniformly across the application, regardless of the specific functionality of each component.

Spring Security Interview Questions for Experienced

15. Could you explain what the Spring Expression Language (SpEL) is?


stands for Spring Expression Language, which is a powerful expression language that supports querying and manipulating objects at runtime. It is used by Spring Security to define access control expressions that can be used to configure authorization rules for any given application. SpEL provides a rich set of operators, functions, and constructs for building expressions that can be used in the configuration files or annotations of a Spring application.

With SpEL, developers can define complex expressions to evaluate runtime properties and enable flexible security configurations. For example, SpEL can be used to grant access only to users with a specific role, to check the IP address of incoming requests, or to evaluate the values of custom user attributes. Overall, SpEL is a valuable feature of Spring Security that enhances the flexibility and customizability of access control for enterprise applications.

Allowed security annotations that can use SPEL

Here is a list of security annotations that are allowed to use Spring Expression Language (SPEL):


- used to pre-authorize access to a method or class based on a security expression


- used to post-authorize access to a method or class based on a security expression


- used to filter method arguments before method execution based on a security expression


- used to filter method results after method execution based on a security expression


- used to specify a list of roles or privileges required to access a method or class

Using SPEL with these security annotations allows for more fine-grained control over access to sensitive parts of your application.

Explanation of AuthenticationManager in Spring Security

In Spring Security, AuthenticationManager is an interface that provides a way to authenticate a user with a set of credentials, such as a username and password. It sits at the heart of the authentication process and is responsible for authenticating the user's credentials against a specified authentication source, such as a database or LDAP server.

The AuthenticationManager interface has only one method, authenticate(), which accepts an Authentication object containing the user's credentials and returns an Authentication object representing the authenticated user. The Authentication object can be further populated with additional information about the user, such as their roles or authorities.

Several implementations of AuthenticationManager are provided by Spring Security, such as ProviderManager and AuthenticationManagerBuilder. The ProviderManager delegates authentication requests to a chain of AuthenticationProvider objects until one is able to successfully authenticate the user. The AuthenticationManagerBuilder simplifies the configuration process by allowing the developer to easily specify the authentication mechanism and authentication source.

In summary, the AuthenticationManager interface is a core component of Spring Security that provides a standardized authentication mechanism for verifying user credentials.

Explanation of ProviderManager in Spring Security

In Spring Security, ProviderManager is a class that provides a way to authenticate and authorize users. It manages a list of AuthenticationProvider objects, each of which can authenticate a specific type of authentication request.

ProviderManager checks each provider in the list to determine if it can authenticate the requested authentication object. If a provider is found that can authenticate the request, it will be used to perform the authentication. If none of the providers can authenticate the request, an AuthenticationException will be thrown.

ProviderManager is responsible for handling authentication failures by calling the registered AuthenticationFailureHandler. It also handles successful authentication by calling the registered AuthenticationSuccessHandler.

Overall, ProviderManager plays a crucial role in the Spring Security framework by managing the authentication process for different types of authentication requests and delegating to the appropriate AuthenticationProvider.

Overview of Spring Security Filter Chain

The Spring Security Filter Chain is a series of filters that protect your Spring application from various types of attacks. These filters perform tasks such as authentication, authorization, csrf protection, and more. The filter chain is typically defined in an XML or Java configuration file and can be customized to suit the needs of your application. Understanding how the Spring Security Filter Chain works is essential for developing secure web applications.

Explanation of how the Security Filter Chain works

The Security Filter Chain is an essential component of a secured web application because it is responsible for processing incoming requests of the web application and ensuring that they are authorized and authenticated based on the defined security rules.

Here's how Security Filter Chain works:

1. The incoming request is intercepted by the Security Filter Chain.

2. The Security Filter Chain examines the request and decides which security filter needs to be executed first based on the order defined in the security configuration.

3. The first security filter examines the request and decides whether to pass it on to the next filter in the chain or to deny the request.

4. If the request is allowed to pass, it is passed on to the next security filter in the chain, and the process starts again until all the security filters have been executed.

5. Once the request has passed through all the security filters without being denied, it is then passed to the servlet container to process it further.

6. If any security filter in the chain denies the request, the processing stops and the user is returned an error response.

By using the Security Filter Chain effectively, web applications can be secured from malicious attacks, unauthorized access, and can ensure a safe environment for users to interact with the application.

Predefined Filters in Spring Security and Their Functions

In Spring Security, there are several predefined filters that can be used to handle various security-related tasks, including:

1. AnonymousAuthenticationFilter - This filter creates an anonymous authentication object for the user if they are not already authenticated.

2. BasicAuthenticationFilter - This filter handles the basic authentication scheme, which involves transmitting a username and password in the request headers.

3. ConcurrentSessionFilter - This filter ensures that a user is only allowed to have one session at a time.

4. CSRFFilter - This filter protects against Cross-Site Request Forgery (CSRF) attacks by creating a unique token for each user session.

5. ExceptionTranslationFilter - This filter catches any exceptions thrown during the authentication chain and translates them into appropriate HTTP responses.

6. LogoutFilter - This filter handles the logout process, which involves invalidating the user's session and removing any authentication objects.

7. UsernamePasswordAuthenticationFilter - This filter handles the authentication process for usernames and passwords submitted via a login form.

8. SessionManagementFilter - This filter manages user sessions and provides protection against session fixation attacks.

9. RequestCacheAwareFilder - This filter allows the user's request to be cached before authentication takes place, preserving the request and redirecting the user back after successfull authentication.

These predefined filters in Spring Security are highly customizable and can be combined or extended as required to facilitate various use cases within an application.

Understanding the Concept of Principal in Spring Security

In Spring Security, a principal is an entity that represents a user, device, or system process that interacts with a web application. It encapsulates the identity and authentication information of the entity and is used by the framework to enforce access control and authorization policies. A principal is typically associated with a set of roles or permissions that determine the actions that the entity is allowed to perform within the application.

In code, the principal object is represented by the interface `` or its implementation ``. These classes provide the necessary methods to retrieve the name, authorities, and other details of the principal. The Spring Security framework uses the principal object in conjunction with a set of rules to grant or deny access to specific resources or functionality within the application.

Understanding the concept of principal in Spring Security is essential for developing secure web applications that enforce access control and authentication policies effectively.

Explanation of DelegatingFilterProxy in Spring Security

DelegatingFilterProxy is a class in Spring Security that helps integrate Spring Security with a web application container. It acts as a filter that delegates the filtering to a target filter bean defined in the Spring application context. The main purpose of DelegatingFilterProxy is to allow Spring Security to take control of the filter chain and apply security measures to the application.

When a request is made to the application, the application container first checks if there is any filter in the filter chain that can handle the request. If the filter is not found in the filter chain, the container throws an exception. This is where DelegatingFilterProxy comes in - it delegates the filtering request to the target filter bean defined in the Spring application context. This bean is responsible for handling the request and performing any necessary security checks.

One of the advantages of using DelegatingFilterProxy is that it allows the filter chain to be configured without requiring direct coupling to the Spring Security implementation. This makes it easier to maintain the application and upgrade the Spring Security version if needed.

Overview of FilterChainProxy in Spring Security

FilterChainProxy is a class in Spring Security that is responsible for managing and executing a sequence of filters. These filters are responsible for enforcing security constraints on incoming requests and outgoing responses. The filters can handle authentication, authorization, and other security-related tasks.

The FilterChainProxy operates by maintaining a chain of filter beans, where each filter bean has its own designated task to perform. When a request is received by the application, the FilterChainProxy is responsible for processing the request through the filters in the chain until the request has successfully passed through all of them.

Each filter in the chain performs a specific task, such as user authentication or resource authorization. The filters may also modify the request or response based on the security requirements.

FilterChainProxy is an essential component of the Spring Security framework, as it provides a flexible and customizable way of implementing security constraints in an application.

Understanding Intercept-URL Pattern and its Necessity

The intercept-url pattern is a configuration element in the Spring Security framework used to secure URLs based on specific criteria defined by the user. It is necessary to specify the intercept-url pattern to determine which URLs to secure and how to secure them. The pattern includes attributes such as the access control list (ACL), which specifies the roles and permissions allowed for accessing particular URLs.

Additionally, the intercept-url pattern enhances security in web applications by adding extra layers of authentication and authorization. Using this configuration element, we can restrict users from accessing sensitive information and ensure that only authorized persons can carry out certain tasks. This is particularly useful when dealing with sensitive data, such as financial or personal information.

In summary, the intercept-url pattern is an important component of the Spring Security framework that helps secure web applications by defining which URLs to secure and how to secure them based on the user's defined criteria.

Order of intercept-url pattern in Spring Security

In Spring Security, the order of intercept-url patterns does matter. The specific patterns should be listed before the more generic ones to avoid any conflicts.

For example, if we have two intercept-url patterns:

<intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/**" access="isAuthenticated()" />

Here, the `/admin/**` pattern should come before `/**` because `/**` pattern matches any URL, including `/admin/**`.

Therefore, if we put `/**` before `/admin/**`, it will match with all URLs, including `/admin/**` and unauthorized users can access the `/admin/**` pages.

In conclusion, we must always list specific patterns before more generic ones to ensure that the more specific patterns take precedence, and avoid any conflicts.

Explanation of the difference between ROLE_USER and ROLE_ANONYMOUS in a Spring intercept-url configuration

In a Spring intercept-url configuration, ROLE_USER and ROLE_ANONYMOUS are roles used to restrict access to certain URL patterns. ROLE_USER is the role assigned to authenticated users, whereas ROLE_ANONYMOUS is the role assigned to unauthenticated users.

When an authenticated user tries to access a URL pattern that is restricted to ROLE_USER, they will be granted access if they have this role. On the other hand, if an unauthenticated user (i.e., a user who has not logged in) tries to access a URL pattern that is restricted to ROLE_USER, they will be redirected to a login page or denied access altogether.

To summarize, ROLE_USER is used to restrict access to authenticated users only, while ROLE_ANONYMOUS is used to restrict access to unauthenticated users only.

Difference between @PreAuthorize and @Secured in Spring Security

In Spring Security, both the @PreAuthorize and @Secured annotations are used for authorization. However, there are some differences between them.

1. Expression Language Support: @PreAuthorize annotation supports the use of expression language (SpEL), while @Secured does not.

2. Fine-grained control: @PreAuthorize provides more fine-grained control over the method access control. You can specify any expression that evaluates to a Boolean value. In contrast, @Secured has a coarse-grained approach and can only specify a single role required to perform the method.

3. Parameter-Based Security: @PreAuthorize allows you to perform parameter-based security checks, whereas @Secured does not provide such capability.

4. Accessing Security Context: @PreAuthorize allows you to access the security context in the expressions. On the other hand, @Secured doesn't provide such access.

Here's an example of how @PreAuthorize can be used to restrict access to a method based on a user's role:

public void deleteOrder(long orderId) {

This method can only be accessed by a user who has the role "ROLE_ADMIN".

Similarly, @Secured can be used to restrict access to a method based on roles, as shown below:

public void deleteOrder(long orderId) {

This method can only be accessed by a user who has the role "ROLE_ADMIN".

Difference between @Secured and @RolesAllowed




are both annotations used for security purposes in Spring Security. However, there are a few differences between them.



annotation is used to annotate a method or class to indicate that access to that resource is restricted to only certain roles. The roles are passed as arguments to the annotation, and if the current user does not have one of the specified roles, access will be denied.

On the other hand, the


annotation is also used to restrict access to a method or class, but it allows for more granular control. Instead of passing in a list of roles as arguments, this annotation allows you to specify individual roles as strings.

Another key difference between these annotations is that


is Spring-specific, while


is part of the standard Java EE security annotations.

Therefore, if you are using Spring Security and want to restrict access to a resource based on user roles, you can use either annotation. However, if you need more granular control over which roles are allowed,


may be a better choice.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.