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:

  • Header
  • Payload
  • Signature

For example, a JWT looks like below:

NiIsInR5cCI6IkpXVCJ9 . eyJzdWIiOiIibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ . SflKxwRJSMeKKF2QT4fwpMeJf36

  • NiIsInR5cCI6IkpXVCJ9: This is the header part and contains the algorithm and what type of token it is.
  • eyJzdWIiOiIibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ: This is the data part (payload).
  • SflKxwRJSMeKKF2QT4fwpMeJf36: This is the signature part. It is used to verify that the data or message does not change during the information transformation.

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.

  • OAuth2 is an authorization framework, and it enables applications such as Facebook, Twitter for obtain limited access to user accounts on HTTP service.
  • OAuth2 provides authorization flows and not the authentication.
  • This works by assigning the user’s authentication to the service that manages the user account and authorizes third-party applications to access that user account.
  • OAuth2 is the most widely used form of OAuth.

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,

  • We can add authentication to applications and secure services with very minimal effort.
  • We don’t have to deal with user retention or user adoption.
  • It provides strong authentication, user management, authorization etc.
  • We can configure Keycloak with Spring Security by adding the Spring Security Adapter.

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:

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

  • AuthenticationManager is the API that describes that how Spring Security’s filters perform authentication.
  • ProviderManager is the mostly used implementation of AuthenticationManager.
Java
@Override
public void configure(AuthenticationManagerBuilder auth)
    throws Exception
{
    auth.inMemoryAuthentication()
        .withUser("admin")
        .password("{noop} w3wiki")
        .authorities("USER");
}

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

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:

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

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

  • This interface is responsible for retrieving user information from a backend data source, such as a database.
  • This returns an instance of the UserDetails interface.
  • It has a single method called loadUserByUsername(). It takes a username as a parameter, and it returns a UserDetails object.
  • The UserDetails object represents the authenticated user, and it contains all the details such as the username, password, authorities (roles) etc.

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

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

  • By using these two annotations, we can easily secure the methods.
  • We can ensure that only the authorized users can have access to them.

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

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

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


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

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