Spring Security Interview Questions List in 2020

This article is targeted towards providing a comprehensive list of Spring Security Interview questions, which are typical to be asked in an interview.

Current article is a part of our series on Spring Interview Questions.

Here you will find the list of questions and answers, not only on Spring Security, but also on Outh2 and Spring Boot Security.

Although, Spring Security is not a regular interview topic. Interviewer will ask the questions on this only if the job requires it or you have it in your resume.

So, if you are one of them, let’s take a deep dive into Spring Security interview questions, right away.

This article should be good enough for both freshers as well as experienced developers and tech leads.

Spring Security Interview Questions and Answers

Spring Security Interview Questions And Answers

1. What is Spring Security? Explain in detail.

Spring Security is a Spring project to support Authentication, Authorization and defense against common exploits, in a Spring based web application.

It has become a de-facto standard for securing Spring based web applications, now-a-days.

2. What is Authentication?

Authentication is the process wherein a system validates “Who are you”.

First, user of the web application provides the Principal and Credentials and then the application validates the user on that Credentials.

Authentication is always precursor to Authorization.

3. What is Authorization?

Authorization is the process of validating “What resources can you access” in the application.

After a user authenticates successfully with specific Credentials, the system provides certain set of authorities configured for the user.

With the help of these authorities, user can access certain set of resources.

These set of authorities are captured in terms of a Role.

Spring Security Authentication vs Authorization

4. How do we plug-in Spring Security into Servlet container?

In the foundation, Spring Security uses Filter component of Java Servlet API.

Servlets has the concept of FilterChain which has a list of Filters in an ordered manner. An HTTP request first go through the FilterChain and then proceed to the Controllers and handlers.

We just hook a special Spring Security Filter, called DelegationFilterProxy in the Servlet‘s FilterChain and then process the security related logic in it.

In this way, all the security related logic gets executed via. DelegationFilterProxy and it’s helper components.

Using Servlet Filter as the base also means that we can plug-in Spring Security into a Servlet application without using Spring container and other modules.

What you will require is just Servlet container to run this application and that’s it.

5. What is DelegatingFilterProxy in Spring Security?

It is one of the most popular Spring Security Interview Questions.

DelegatingFilterProxy is the entry point of Spring Security in a Java web application.

As already discussed, Spring Security is based on the concept of Servlet filters. So, DelegationFilterProxy is a Servlet Filter implementation which works as a root Filter.

DelegateFilterProxy in Spring Security

We register DelegationFilterProxy with the web application like this:

<filter>
<filter-name>rootSecurityFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>rootSecurityFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

By doing this, it also works as bridge between web application and Spring IoC container (ApplicationContext) and it’s lifecycle.

Once registered, it delegates all it’s work to a special Spring bean which is again a Filter implementation registered with Spring Container.

If you want to understand it more deeply: here is the recommended link.

6. What is FilterChainProxy in Spring Security?

FilterChainProxy is a special bean to which DelegatingFilterProxy delegates all it’s incoming HTTP requests.

In this way, you do not need to register all your security filters in web.xml. Instead, declare them in the Spring container under proper FilterChainProxy bean.

FilterChainProxy then forwards all it’s requests to SecurityFilterChain.

filterchainproxy in spring security

7. What is so special about FilterChainProxy?

  1. It works as starting point for all security specific logic.
  2. If we are not sure about debugging point while troubleshooting an issue, we can start from here.
  3. It applies HTTPFirewall.
  4. It performs security logic which is global to the application.
  5. Multiple SecurityFilterChain can be registered to it. In this context, it also takes the decision as to which SecurityFilterChain a request should go.

8. What is SecurityFilterChain in Spring Security?

SecurityFilterChain is a FilterChain component which has zero or more Security Filters in an order.

Spring Security FilterChain, DelegationFilterProxy and SecurityFilterChain

9. Name some of the built-in Security Filters?

Out of several, here are few Security Filters provided by Spring Security:

  1. X509AuthenticationFilter
  2. OAuth2LoginAuthenticationFilter
  3. Saml2WebSsoAuthenticationFilter
  4. UsernamePasswordAuthenticationFilter
  5. DigestAuthenticationFilter
  6. BasicAuthenticationFilter

From here starts Spring Security interview questions on the internals of Authentication and Authorization. Answers on all these are very much expected from a candidate.

10. What is SecurityContext in Spring Security?

SecurityContext is an object which holds the information of Authenticated user.

11. What is SecurityContextHolder?

It is a wrapper object for SecurityContext and SecurityContextHolderStrategy.

12. What is SecurityContextHolderStrategy?

It represents the strategy by which SecurityContext will be created. In a typical security scenario, it is ThreadLocal.

13. What are different SecurityContextHolder strategies?

  1. one is threadLocal
  2. second, inheritable threadLocal
  3. and third is, Global

14. Explain the structure of Authentication object in Spring Security.

Authentication is an interface.

We have different types of objects depending upon different Authentication implementations.

All these implementations have 3 parts:

  1. Principal
  2. Credentials
  3. Authorities

15. What is Principal?

A Principal represents a user’s identity.

It can be a String object having username on a simple level or a complex UserDetails object.

16. What is Credentials?

In simple terms, a Credential is a Password.

17. What are Authorities in Authentication object?

A user is given zero or more GrantAuthority depending upon it’s access rights.

Look them as different roles a user is assigned to.

Authentication object holds Collection of such GrantAuthority.

SecurityContextHolder, SecurityContext, Authentication Object

18. What is AuthenticationManager in Spring Security?

AuthenticationManager is a Spring Security component which tells “How Authentication will happen”.

As the How part is dependent on which Authentication provider we are using for our application, an AuthenticationManager has the reference to all the AuthenticationProviders.

19. What is ProviderManager in Spring Security?

A ProviderManager is one of the commonly used implementation of AuthenticationManager.

It has the list of Authentication to serve the request’s authentication.

ProviderManager and Authentication Provider

20. What is AuthenticationEntryPoint?

What happens when a user tries to access a URL/ resource but hasn’t authenticated yet?

We typically send the user back to some form to fill in the login details. Right?

Now, that is AuthenticationEntryPoint. It is entry point to access the application resources.

21. Who checks the user access of a resource?

FilterSecurityInterceptor in the SecurityFilterChain does this job.

22. Who checks the user access of a resource?

FilterSecurityInterceptor in the SecurityFilterChain does this job.

If user does not have access, it raises the exception.

23. Where do we configure AuthenticationEntryPoint?

We configure it with ExceptionTranslationFilter.

When FilterSecurityInterceptor raises the exception, ExceptionTranslationFilter handles it and sends the configured AuthenticationEntryPoint to the user as response.

24. How to protect passwords in a secured web application?

To protect the password:

  1. First thing we should do is not to have passwords in plain text.
  2. We should use hashing or salting as preventive measure.

and Spring Security supports both hashing and Salting.

25. What is Hashing in Spring Security?

Hashing is a general security concept wherein we convert a String into an encoded string, according to the Hashing algorithm used.

There are many Hashing algorithms which can be applied.

Hashing method should take password as input and outputs the hashed string. This hashed string should be stored in DB instead of plain text.

Whenever user provides password to authenticate, in the back-end, we convert that password to the hashed string using the same hashing algorithm, and then match this to the stored string in the DB.

26. What is Salting and why do we use the process of Salting?

So, even if hashing decrease the possibility of password hack still hackers have found a way around it.

For this, they use is called Rainbow tables. Rainbow tables has already computed hash string of possible passwords. Hacker apply brute force with this input.

Solution for securing the app from this? Salting.

Salting the process wherein we add an extra string with password to the hashing algorithm. And just by doing that, it is kind of impossible to get the combination of Password and Salt in the rainbow table.

Hashing And Salting in Spring Security

27. What is “intercept-url” pattern?

<intercept-url> is the tag to configure authorization or access-control in a Spring Security application.

An example being:

<http realm="An example" use-expressions="false">
    <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
    <intercept-url pattern="/**" access="ROLE_USER"/>
</http>

28. What is expression based access control in Spring Security?

We can use Spring EL expressions to define our authorization configuration. To enable this Spring Security provides us different controls like: hasRole, hasAnyRole, isAuthenticated, permitAll.

For example:

<http realm="An example" use-expressions="true">
    <intercept-url pattern="/login.jsp*" access="permitAll()"/>
    <intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
</http>

Advantage of using expression based access-control is that it allows us abstract complicated boolean logic in a single expression.

29. How to restrict URL access in Spring Security?

Example:

<http realm="An example" use-expressions="true">
    <intercept-url pattern="/login.html*" access="permitAll()"/>
    <intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
</http>

In the above example, to access any URL (except login.html), user should have the role of ROLE_USER. Otherwise, he/she will not be able to access the URL.

In this way, we are restricting the access to the URL.

30. Does order matter in intercept-url pattern?

Yes. Ordering is very very important when we have multiple intercept-url patterns.

Let’s say we change the order of pattern from this:

<http realm="An example" use-expressions="true">
    <intercept-url pattern="/login.html*" access="permitAll()"/>
    <intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
</http>

to this:

<http realm="An example" use-expressions="true">
    <intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
    <intercept-url pattern="/login.html*" access="permitAll()"/>
</http>

Now, if user access login.html, our application will match it to the /** pattern, which will PASS. Now, user must have role of ROLE_USER to access the login.html page.

Application will never match the pattern at 2nd line.

Hence the thumb rule is to define the pattern in the order of most specific to least specific (general).

31. Does order matter in intercept-url pattern?

Yes. Ordering is very very important when we have multiple intercept-url patterns.

32. What is the difference between hasAuthority and hasRole?

hasAuthority(‘ROLE_USER’) is similar to hasRole(‘USER’) after Spring Security 4. Prefix ROLE_ will automatically be added to it in case of hasRole.

So, it is just a semantic change in this context.

33. What is PreAuthorize?

PreAuthorize is a method level annotation which is used to restrict the access to the method invocation.

For example:

@PreAuthorize("hasRole('ROLE_USER')")
  public void aMethod(Params params);

Is user does not have the role of ROLE_USER, then application will not be able to invoke this method during this user activities.

This annotation is part of Method security expressions. Others being: PostAuthorize, PreFilter, PostFilter.

Spring OAuth2 Interview Questions And Answers

34. What is OAuth 2.0 ?

OAuth, also called Open Authorization, is an industry-standard protocol for Authorization.

It enables third-party applications get limited access on the user information.

It does so with the help of four components also called OAuth roles:

  1. Authorization Server
  2. Resource Server
  3. Resource Owner or User
  4. Client (client application)

The OAuth2 protocol is all about how these different roles communicate with each other and completes the goal of limited access-control.

35. How does OAuth 2.0 works?

Suppose, you are User (Resource Owner). You are using any website which has option to e.g. “log-in with Google” facility.

So, Google will have Authorization and Resource server. User will be registered with Google.

Now this is how it works( NOTICE THE ARROW DIRECTION ):

  1. Client -> User : Client asks for Authorization request from the User.
  2. Client <- User: User provides Authorization grant to the Client.
  3. Client -> Authorization Server: Client sends this Authorization Grant to the Authorization Server.
  4. Client <- Authorization Server: Authorization Server sends access token to the Client.
  5. Client -> Resource Server: Client sends access token to the resource server.
  6. Client <- Resource Server: Resource Server sends the resource to the Client.
oauth2 protocol working

Here are some of the Spring Security interview questions based on Spring Boot.

36. What is Spring Security OAuth2?

Spring Security OAuth2 is a sub-project under Spring Security whose target is to help build OAuth2 enabled Consumer and Provider Java application.

We can add Spring Boot starter projects to enable Spring Security OAuth2 in Spring Boot.

37. How to enable Spring Boot Security in a Spring Boot project?

There are multiple ways in which we can configure Spring Boot Security in a Spring Boot project. Here is one example:

Step 1: Add the starter dependency.

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

Step 2: Extend WebSecurityConfigurerAdapter and create a config class.

public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
}

Step 3: Annotate it with @Configuration.

@Configuration
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
}

Step 4: Enable WebSecurity.

@EnableWebSecurity
@Configuration
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
}

Step 5: Override WebSecurityConfigurerAdapter methods and provide your custom logic.

@EnableWebSecurity
@Configuration
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http
         .authorizeRequests()
         .antMatchers("/").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/customURL")
            .permitAll()
   }
}

38. How to create an OAuth2 client with Spring Boot Security?

Please checkout this guide to understand the code.

You will need to import Spring Boot OAuth2 Starter project first:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

Then you will need to implement WebSecurityConfigurerAdapter and override “configure” method as it should be.

If you still have got time then checkout this video which will give you a crash course on Spring Security.

And that’s it about Spring Security Interview questions. Hope you got some benefit out of it.

What to read next?

Go through Spring MVC Interview questions or our article on Spring Boot interview questions.

Still not sure? Checkout our series on Spring Interview questions to pick an interview topic which suits your profile.

Best of Luck!!

2 thoughts on “Spring Security Interview Questions List in 2020”

    • Hi Kundan,

      I got curious.

      1. Isn’t it easier to go through website than to handle multiple PDFs for different topics.
      2. Also, website is more permanent to treat it like your notes.

      What’s your thoughts on this?

      Reply

Leave a Comment