Open In App

Spring Security Interview Questions and Answers

Spring Security is a highly flexible and customizable security framework designed for Java applications, particularly those developed using the Spring Framework. It offers extensive security services for enterprise-level Java EE-based software applications. At its Core, Spring Security is concerned with two vital aspects of software application security: authentication, which involves verifying users' identities, and authorization, which involves determining the actions that users are allowed to perform.

In this article, We will look into 30+ Spring Interview Questions and Answers tailored for both freshers and experienced professionals with 1, 5, and 10 years of experience. Here we cover everything about Spring Security Interview Questions including the basics of authentication and authorization, configuration strategies, cross-site scripting prevention, securing REST APIs, and best practices for using OAuth2 and JWT with Spring Security.

Spring Security Interview Questions

Spring Security Interview Questions And Answer

Spring Security Interview Questions for Freshers

1. What is Spring Security?

Spring Security is an effective, customizable Java framework for authentication, authorization, and access control in Spring-primarily-based applications. It protects our applications from unauthorized access and also manages user permissions.

2. What are the key features of Spring Security?

Some of the core features of Spring Security are depicted below:

3. Difference between Authentication and Authorization in Spring Security.

Features

Authentication

Authorization

Definition

It is a process used to verify user's identity.

It determines that within the application, which task a user is allowed to do.

Working

Checks credentials like username and password provided by user against stored credentials.

To determine resources, it uses user's identity and pre-defined access control rules.

Performance

It is fast.

After authentication, it authorizes.

Result

User gets authenticated and security token granted to them.

Users get access to specific features based on the rules.

Below is a simple diagram to know about Authentication and Authorization.

Authentication and Authorization

Know more about Authentication and Authorization in Spring Security

4. How to configure Authentication in Spring Security?

To configure Authentication in Spring Security (not basic authentication) we need to follow below procedure:

5. How to configure Authorization in Spring Security?

To configure Authorization in Spring Security, follow the below procedure:

@Override
protected void configure(HttpSecurity http) throws Exception
{
    http.authorizeRequests()
        .antMatchers("/author/admin")
        .hasRole("ADMIN")
        .antMatchers("/author/user")
        .hasRole("USER")
        .antMatchers("/")
        .permitAll()
        .and()
        .formLogin();
}

6. What is the Latest Version of Spring Security and What's New in It?

Spring Security 6 is the latest version of Spring Security and it has introduced many new features. Following are the most useful features that are introduced in Spring Security 6.

7. Explain basic authentication in Spring Security.

Below are the steps to implement basic authentication using username and password.

@EnableWebSecurity
public class MySecurityAppConfig
    extends WebSecurityConfigurerAdapter {

    // Configure the basic authentication through configure
    // method
    @Override
    protected void configure(HttpSecurity http)
        throws Exception
    {
        http.authorizeHttpRequests()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
    }
}

Now, the application has basic authentication using the provided username and password.

Know more about Basic Authentication in Spring Security

8. How to Enable and Disable CSRF in Spring Security?

Cross-Site Request Forgery (CSRF) is an attack. End users performs unwanted actions on a web application in which they are currently authenticated, and it is caused due to this web attack. It is one of the most severe vulnerabilities in Spring Security. If we want to enable or want to disable the CSRF protection in Spring Security, we have to configure it in the application’s security configuration class. Below is the code sample for enable and disable this:

@Configuration
public class GFG extends WebSecurityConfigurerAdapter {
    --------Your Code-- -------@Value(
        "${security.enable-csrf}")
          private boolean csrfEnabled;
    --------Your Code-- -------

          @Override protected void
          configure(HttpSecurity http) throws Exception
    {
        super.configure(http);
        if (!csrfEnabled) {
            http.csrf().disable();
        }
    }
}

Note: In Spring Security, by default the CSRF (Cross-Site Request Forgery) protection is enabled.

Know more about:

9. What is a Filter Chain in Spring Security?

To perform most of the security features, Spring Security utilizes the filter chain. Internally Spring Security maintains a filter chain with each filter having a specific responsibility. Filters are added or removed from the system depending on needed services. This is how the filter chain works in a web application:

Filters Chain

In the above image,

Know more about Spring Security – Filter Chain with Example

10. When to Use Spring Security antMatcher()?

The antMatchers() is used to configure the URL paths. The URL paths either can be permitted or denied to the user’s http request. It will be done according to the role or the authorization of that particular user. Following are the rules applied on antmatchers():

Following are the rules applied on antmatchers():

Know more about Spring Security – Securing Endpoints Using antMatchers()

11. How to implement Spring Security in a simple Spring Boot application?

To implement Spring Security in any Spring Boot application is by adding the following starter dependency in the pom.xml file.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>6.2.0</version>
</dependency>

Know more about Simple Authentication in Spring Boot

12. How to configure Spring Security in Spring MVC application?

To configure Security in a Spring MVC application, follow the below steps:

13. How to Deny Access to All URLs in Spring Security?

To Deny Access to All URLs in Spring Security we can use denyAll() Spring Security Expressions.

Spring’s expression-based access Control has an expression called denyAll which evaluation is always false. To know that how to use this expression follow the below syntactical example:

@Override
protected void configure(HttpSecurity http) throws Exception
{
    http.authorizeHttpRequests()
        .anyRequest()
        .denyAll()
        .and()
        .httpBasic();
}

Know more about Spring Security – Deny Access to All URLs

14. How to Get the Current Logged in User Details in Spring Security?

We can get the Current Logged in User Details in Spring Security with the help of the Authentication class. A sample code is given below.

// Principal means username
@GetMapping("/")
public String helloGfg(Principal principal,
                       Authentication auth, Model model)
{

    // Get the Username
    String userName = principal.getName();
    System.out.println("Current Logged in User is: "
                       + userName);

    // Get the User Roles/Authorities
    Collection<? extends GrantedAuthority> authorities
        = auth.getAuthorities();
    System.out.println("Current Logged in User Roles are: "
                       + authorities);
    model.addAttribute("username", userName);
    model.addAttribute("roles", authorities);
    return "home-page";
}

Know more about Spring Security – Get the Current Logged in User Details

15. What is Spring Security Password Encoder?

Servlet support in Spring Security includes storing passwords securely by integrating a PasswordEncoder. We can configure the PasswordEncoder implementation of Spring Security by exposing the PasswordEncoder Bean. A sample code is given below.

@Configuration
@EnableWebMvc
@ComponentScan("com")
public class MySecurityAppConfig {
    @Bean PasswordEncoder getPasswordEncoder()
    {
        return new BCryptPasswordEncoder();
    }
}

There are various types of Password encoder available in Spring Security

Know more about Spring Security - Password Encoder

16. Explain the purpose of @EnableWebSecurity in Spring Security.

@EnableWebSecurity annotation gives signals to Spring to enable its web security support.

@Configuration
@EnableWebSecurity
public class SecurityConfig
    extends WebSecurityConfigureAdapter {
    @Override
    protected void configure(HttpSecurity http)
        throws Exception
    {
        http.authorizeRequests()
            .antMatchers("/hello")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .formLogin();
    }
}

Spring Security Interview Questions for Intermediate

17. What is JWT in Spring Security?

JWT stands for JSON Web Token. It is widely used to exchange information between two ends as a JSON object. It securely transforms informations. It is mostly used in the case of Authorization and Information Exchange. It consists of three parts:

For example, a JWT looks like below:

NiIsInR5cCI6IkpXVCJ9 . eyJzdWIiOiIibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ . SflKxwRJSMeKKF2QT4fwpMeJf36

JWT

To know more please refer to these articles:

18. What is OAuth and OAuth2 in Spring Security?

OAuth is an open standard protocol and it is used for authorization. OAuth2 is a version of OAuth.

OAuth Architecture

19. What is Keycloak and explain the integration of keycloak with Spring Security?

Keycloak is an open-source IAM (Identity and Access Management) solution. It is developed by Red Hat. By using this,

For example:

Add the dependency:

<dependency>    
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-security-adapter</artifactId>
<version>21.1.2</version>
</dependency>

Java Configuration Class:

@KeycloakConfiguration
public class SecurityConfig
    extends KeycloakWebSecurityConfigurerAdapter {
    @Autowired
    public void
    configureGlobal(AuthenticationManagerBuilder auth)
        throws Exception
    {
        auth.authenticationProvider(
            keycloakAuthenticationProvider());
    }
    @Bean
    @Override
    protected SessionAuthenticationStrategy
    sessionAuthenticationStrategy()
    {
        return new RegisterSessionAuthenticationStrategy(
            buildSessionRegistry());
    }
    @Bean protected SessionRegistry buildSessionRegistry()
    {
        return new SessionRegistryImpl();
    }
    @Override
    protected void configure(HttpSecurity http)
        throws Exception
    {
        super.configure(http);
        http.authorizeRequests()
            .antMatchers("/customers")
            .hasRole("USER")
            .antMatchers("/admin")
            .hasRole("ADMIN")
            .anyRequest()
            .permitAll();
    }
}

To know more please refer to these articles:

20. What is the role of an AuthenticationProvider in Spring Security?

Authentication Providers perform the actual authentication work.

@Override
public void configure(AuthenticationManagerBuilder auth)
    throws Exception
{
    auth.inMemoryAuthentication()
        .withUser("admin")
        .password("{noop} geeksforgeeks")
        .authorities("USER");
}

Here, we are injecting the Authentication Provider that is in order to authenticate a user for the application using inMemoryAuthentication().

Know more about Spring Security - Authentication Provider

21. How to Secure an Endpoint in Spring Security?

In Spring Security, we can secure an endpoint by following below steps:

Step 1: Configure Security

We will create a configuration class that should extend WebSecurityConfigurerAdapter and override the configure() method. For example:

@Configuration
@EnableWebSecurity
public class SecurityConfig
    extends WebSecurityConfigurerAdapter {
    @Override
    private void configure(HttpSecurity http)
        throws Exception
    {
        // complete code
    }
    @Override
    private void
    configure(AuthenticationManagerBuilder auth)
        throws Exception
    {
        // complete as per requirement
    }
}

Step 2: Secure Specific Endpoints

We can use annotations like @PreAuthorize, @Secured @RolesAllowed, etc. to secure specific method or classes. For example:

@RestController
public class MyController {
    @GetMapping("/securedEndpoint")
    @Secured("ROLE_USER")
    public String securedEndpoint()
    {
        //.....
    }
}

Configure Method Security:

We can use the @EnableGlobalMethodSecurity annotation for method level security.

22. Explain UserDetailsService and UserDetails in Spring Security.

In Spring Security, the UserDetailsService is an interface used for loading user-specific data.

Know more about Spring Security – UserDetailsService and UserDetails with Example

23. What is method-level security in Spring Security?

Method-Level security in Spring Security is done by using @PreAuthorize and @PostAuthorize annotations.

@PreAuthorize: It is used to secure a method before it is executed.

@PreAuthorize("hasRole('ADMIN')")
public void deleteEmployee(Long id)
{
    // code
}


Here, only users with Admin role can access the deleteEmployee() method.

@PostAuthorize: It is used to secure a method after it is executed.

@PostAuthorize("hasRole('ADMIN')")
public List<Employee> getAllEmployees()
{
    // code
}


Here, only users with Admin role can view the list of all employees.

Know more about Method-Level security in Spring Security

24. Difference between hasRole() and hasAuthority().

Features

hasRole()

hasAuthority()


Working

It is the shortcut for specifying URLs require for a particular role.

It specifies that URLs require a particular authority.


Prefix

Do not have to add role prefix (default "ROLE_").

Have to add role prefix (default "ROLE_").


Syntax

The role is required (i.e. ADMIN, USER etc.).

The authority to require (i.e. ROLE_ADMIN, ROLE_USER, etc.)

Spring Security Interview Questions for Experienced

25. What is SessionManagement in Spring Security?

At the time of login, user will enter username and password. If that is valid a HTTP session is created servers. That session creation, managing, destroying everything is called Session Management.

26. What is Diligatingfilterproxy in Spring Security?

DiligatingFilterProxy is a Servlet filter that intercepts all the incoming requests sent to an application.

DelegatingFilterProxy-(2)

   <filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
</filter-mapping>

27. How to implement Two-Factor Authentication (2FA) in Spring Security?

To implement two-factor authentication (2FA) follow the below steps:

  • Step 1: Add spring-boot-starter-security dependency in the pom.xml file.
  • Step 2: To configure Spring Security, extend WebSecurityConfigureAdapter (WSCA).
@EnableWebSecurity
public class SecurityConfig
    extends WebSecurityConfigurerAdapter
  • Step 3: Override the configure method.
@Override
protected void configure(HttpSecurity http) throws Exception
{
    // write code here
}
  • Step 4: Now implement two-factor authentication by extending AbstractAuthenticationProcessingFilter. (You may create a custom filter)
public class TwoFactorAuthenticationFilter
    extends AbstractAuthenticationProcessingFilter
  • Step 5: Register the custom filter in Security Configuration.
.addFilterBefore(
    new TwoFactorAuthenticationFilter(),
    UsernamePasswordAuthenticationFilter.class);


  • Step 6: Based on the application requirements, enable two-factor authentication for specific users or groups.

Know more about Two-Factor Authentication in Spring Security

28. Explain Hashing in Spring Security.

Generally, end-users register the details at the same time provides password as well. That password we store in the database as it is that is called Plain text.

Hashing

29. What is Spring Expression Language (SpEL) and Tell Some Spring Security Annotations that are involved with this?

SpEL (Spring Expression Language) is a powerful expression language and also this supports querying and manipulating an object graph at runtime. It can be used within Spring annotations, and it provides dynamic values based on runtime data. There are some Annotations that are involved with Spring Security

Know more about Spring Expression Language (SpEL)

Bonus Spring Security Questions and Answers

30. How Spring security handles user authentication?

Spring security handles user authentication by verifying and managing credentials, filters. Spring Security has UserDetailsService, this service takes the username and returns an object with the user details.

31. Explain potential web application vulnerabilities and how Spring Security mitigates them?

Spring Security protects against common web application vulnerabilities like:

Spring Security mitigates them through filters and Content Security Policy.

32. How to implement Spring Security with in-memory user storage.

To implement Spring Security with in-memory user storage, follow the below steps:

Step 1: Add Starter dependency in XML file.

 spring-boot-starter-security

Step 2: In Spring Security configuration, enable in-memory authentication.

auth.inMemoryAthentication()

Know more about Spring Security - In-Memory Authentication

33. Explain @PreAuthorize and @PostAuthorize annotations.

Know more about Spring Security - Annotations

34. How to troubleshoot common Spring Security errors?

To troubleshoot common Spring security errors,

35. Explain Salting and its usage.

Note: Salting is automatically applied since Spring Security version 3.1.

Conclusion

In conclusion, mastering Spring Security interview questions is essential for both beginners and seasoned professionals. These questions help you understand the framework and its importance in creating secure software. By exploring these topics, you not only prepare for interviews but also improve your knowledge of vital security principles.

Remember, learning Spring Security is an ongoing process, whether you're new to the field or have years of experience. Embrace the challenge, enhance your skills, and face each interview with confidence. With persistence and practice, you can excel in Spring Security interviews at any career stage.

Spring Security Interview Questions - FAQs

What is the role of Spring Security in application development?

Spring Security provides authentication and authorization services for Java applications, ensuring secure access to resources.

What types of authentication does Spring Security support?

Spring Security supports a variety of authentication methods including form-based authentication, LDAP, basic authentication, OAuth2, and JWT among others.

What are the essential configurations required for Spring Security?

Essential configurations include setting up a SecurityContextHolder, AuthenticationManager, and configuring HttpSecurity to specify URL access rules and linked authentication and authorization requirements.

How can I prepare for a Spring Security interview?

Prepare by understanding core concepts of Spring Security, practicing with real-world scenarios, and familiarizing yourself with common problems and their solutions in Spring Security.

How can I stand out in a Spring Security interview?

Demonstrate a deep understanding of security principles, share experiences of solving complex security problems, and show your familiarity with the latest updates and best practices in Spring Security.

Article Tags :