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.

  • It performs error handling, protects the resources, and manages login authentication. Those are the principal functions of Spring Security. 
  • It has a flexible configuration, secure applications, and smooth and easy integration.
  • This is broadly used in enterprise applications.

2. What are the key features of Spring Security?

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

  • Authentication: Process of Identifying the person trying to access the application.
  • Authorization: Process of Identifying if the person is allowed to do this operation.
  • Principal: To know, is the person that we have identified through an authentication process. It is also called the Currently logged-in user that we store in session.
  • Protection: This protects against most common threats like cross-site scripting and SQL injection.
  • Granted Authority: These are the groups of permissions that are allowed for a user.

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.

4. How to configure Authentication in Spring Security?

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

  • Extend WebSecurityConfigureAdapter in a custom class and use @EnableWebSecurity annotation.
  • Overrides configure(AuthenticationManagerBuilder) method.
  • Configure type of auth, user, password and role.
  • Now, this will automatically create and configure a new Authentication Manager and then Spring Security will use this Authentication Manager instead of using the default one.

5. How to configure Authorization in Spring Security?

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

  • Extend WebSecurityConfigureAdapter in a custom class and use @EnableWebSecurity annotation.
  • Overrides configure(HttpSecurity) method.
  • Now Configure http.authorizeRequests()
Java
@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.

  • Now we can automatically enable .cors() if CorsConfigurationSource bean is present
  • It simplifies the configuration of the OAuth2 Client component model
  • It will improve the detection of CVE-2023-34035
  • It added OIDC Back-channel Logout Support for OAuth 2.0
  • Make Configurable RedirectStrategy status code
  • Make Configurable HTTP Basic request parsing

7. Explain basic authentication in Spring Security.

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

  • Add Spring Security Starter Dependency i.e. spring-boot-starter-security to pom.xml file.
  • Extend WebSecurityConfigureAdapter in a custom class and use @EnableWebSecurity annotation.
  • Override configure(HttpSecurity) method to specify security rules.
Java
@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.

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:

Java
@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:

In the above image,

  • Client sends the request for a resource.
  • The application container creates a filter chain to execute an incoming request.
  • After that each requests i.e. the HttpServletRequest passes through that filter chain based upon the path of the request URI.

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():

  • ? – matches one character.
  • * – matches zero or more characters.
  • ** – matches zero or more directories in a path.

Following are the rules applied on antmatchers():

  • hasAnyRole()
  • hasRole()
  • hasAuthority()
  • hasAnyAuthority()
  • authenticated()
  • anonymous()

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>

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

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

  • Step 1: Add spring-boot-starter-security dependency in the pom.xml file.
  • Step 2: Configure Spring Security by extending WebSecurityConfigureAdapter (WSCA).
  • Step 3: For custom login functionality, create a simple login page.
  • Step 4: Now Run the Spring MVC application, Spring Security will automatically authorize and authenticate the application.

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:

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

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.

Java
// 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";
}

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.

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

There are various types of Password encoder available in Spring Security

  • BCryptPasswordEncoder
  • StandardPasswordEncoder
  • NoOpPasswordEncoder
  • Pbkdf2PasswordEncoder
  • Argon2PasswordEncoder

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

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

  • This makes the application secured.
  • This is used in conjunction along with the @Configuration annotation.
Java
@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 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 And Answer

Table of Content

  • Spring Security Interview Questions for Freshers
  • Spring Security Interview Questions for Intermediate
  • Spring Security Interview Questions for Experienced
  • Bonus Spring Security Questions and Answers

Similar Reads

Spring Security Interview Questions for Freshers

1. What is Spring Security?...

Spring Security Interview Questions for Intermediate

17. What is JWT in Spring Security?...

Spring Security Interview Questions for Experienced

25. What is SessionManagement in Spring Security?...

Bonus Spring Security Questions and Answers

30. How Spring security handles user authentication?...

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....

Spring Security Interview Questions – FAQs

What is the role of Spring Security in application development?...

Contact Us