Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Friday, April 19, 2024

Top 25 Spring Security Interview Questions Answers for Java Developers

Hello guys, Spring Security is one of the most popular security frameworks in the Java world and I strongly believe that every experienced Java developer should learn it. Because of its popularity, there is always some question on Spring Security on Java interviews but there are not enough resources to prepare for that. That's why when  I shared the Spring MVC questions and spring boot interview question last year, a lot of you asked me to share similar interview questions on Spring Security, Spring Cloud, and Microservices. I listen to those requests and have been doing some research since then to write those articles. 

Last week, I published the Spring Cloud Interview questions and Spring Data JPA interview questions and in this article, you will find 25+ frequently asked Spring Security Interview Questions for Java Interviews with answers and explanations. 

You can use this list to not only prepare for a telephonic round of interviews but also for face to face interviews. 

Another good thing about these Security questions is that they also answer the Spring security question from the official Spring Professional Certification Guide. This means you can also use them to prepare for Spring Certification. 

Even if you are not preparing for the Spring Professional certification, you can use questions from this study guide to prepare Spring Security, Spring MVC, and Spring core based upon the topics of Spring Core certification. 

After going through these questions I realize that I have already seen many of them on Java Web development interviews that use the Spring framework for building web applications, and that's why I incorporated them into this list of Spring security interview questions

These questions are good resources to check your existing Spring Security knowledge and at the same time, you can also refresh some important concepts before you appear for any telephonic or face-to-face round of interviews.

Since Spring, or do I say VMware, the company behind Spring also provides Spring Professional certifications for your spring and spring boot skills, it's a good time to get recognition for your Spring expertise. 

As with any certification, the tangible benefits come in terms of recognition but you also learn a lot while preparing for exams.

25+ Spring Security Interview Questions with Answers

Without wasting any more of your time, here is a list of Spring security questions for Java developers. I have organized these questions into three different categories, spring-security basics, questions on authentication and authorization, and questions on password encoding and other miscellaneous spring security features. Each section has 5 to 10 questions for you to practice before the interviews. 

1. Spring Security Basics Interview questions

In order to effectively use the Spring Security library, it's important for you to understand the basics of Spring security and how spring security works. In this section, we'll see some questions on Spring security architecture and in general how does it work. 

1. What is the delegating filter proxy in Spring Security? (answer)
The delegating filter proxy is a generic bean that provides a link between web.xml and application-Context.xml. Spring security uses filters to implement several security related cross-cutting concerns like authentication and authorization. 

Since filters need to be declared in the web.xml so that the Servlet container can invoke them before passing the request to the actual Servlet class.

In Spring security, these filters are also Spring bean so that they can take advantage of Spring's dependency injection features, hence they are declared inside the Spring configuration file and a delegating filter proxy (DelegatingFilterProxy) is declared on their behalf on web.xml as filter as shown below:



At runtime, delegating filter proxy delegates HTTP requests to a bean class for filtering. If you want to learn more, I suggest joining Spring Security Core: Beginner to Guru course on Udemy to learn more about how delegating filter proxy works in Spring security. 

Top 25 Spring Security Interview Questions with Answers for Java Developers

2. What are some restrictions on using delegating filter proxy in Spring security?
In order for DelegatingFilterProxy to work as expected, there are some rules and restrictions which you need to follow like

1) You must declare delegating filter proxy to your web.xml as a filter.

2) The target bean must implement the javax.servlet.Filter interface.

3) The target bean must have the same name as that in the filter-name element.

4) You can also specify a "targetBeanName" filter init-param in web.xml to specify the name of the target bean in the Spring application context.

3. Do Fitler's life-cycle methods like init() and destroy() will be a delegate to the target bean by DelegatingFilterProxy?
No, by default the lifecycle methods defined by the Servlet Filter interface will not be delegated to the target bean, Instead, the Spring application context will manage the lifecycle of that bean. It will be responsible for creating and destroying instances of filter beans. 

Though you can enforce invocation of the Filter.init() and Filter.destroy() lifecycle methods on the target bean by specifying the "targetFilterLifecycle" filter init-param as "true". 

This will let the servlet container manages the filter lifecycle instead of the Spring container.

4. Who manages the life-cycle of filter bean in Spring?
As explained in the previous example, by default Spring container manages the life-cycle of filter beans in Spring i.e. the beans which implements Filter interface and handle request delegated by delegating Spring proxy.

Though, you can ask Servlet container to manage their life-cycle by declaring "targetFilterLifecycle" filter init-param as "true" on web.xml while declaring the DelegatingFilterProxy filter as shown below:



5. What is the security filter chain in Spring Security? (answer)
The Spring Security framework uses a chain of filters to apply various security concerns like intercepting the request, detecting (absence of) authentication, redirecting to the authentication entry point, or pass the request to authorization service, and eventually let the request either hit the servlet or throw a security exception (unauthenticated or unauthorized). 

The DelegatingFitlerProxy glues these filters together and forms the security filter chain. That's why you see the name "springSecurityFilterChain" when we declare DelegatingFilterProxy as a filter in web.xml.  

If you want, you can further see the Learn Spring Security MasterClass course by Eugen Paraschive of Baeldung to learn more about Spring security architecture and essential concepts. 

What is the security filter chain in Spring Security

6. What are some predefined filters used by Spring Security? What are their functions and in which order they occurred?
The Spring security filter chain is a very complex and flexible chain of filters. These filter access services such as UserDetailsService and AuthenticationManager to perform their task. Their orders are also important as you may want to check for authentication before authorization.

Here are some of the important filters from Spring's security filter chain, in the order they occur in:
  • SecurityContextPersistenceFilter - This filter restores Authentication from the JSESSIONID cookie.
  • UsernamePasswordAuthenticationFilter - This filter performs authentication.
  • ExceptionTranslationFilter - This filter catch security exceptions from FilterSecurityInterceptor.
  • FilterSecurityInterceptor - This filter may throw authentication and authorization exceptions.

7. Can you add custom filters in Spring security's filter chain?
Yes, you can add or replace individual filters with your own logic in Spring's security filter chain. Even though Spring Security provides a number of filters by default, and most of the time, these are enough. You may need to implement new functionality depending upon your project's requirement and this can be done by creating a new filter to use in the chain.

8. How to implement a custom filter in Spring Security?
You can implement a custom filter in Spring security by implementing the org.springframework.web.filter.GenericFilterBean class. The GenericFilterBean is a simple javax.servlet.Filter implementation which is Spring aware. You can override doFilter(ServletRequest req, ServletResponse res, FilterChain chain) to implement your own logic.

9. How to add a custom filter into the Spring Security filter chain?
Depending upon whether you are using Java Configuration or Spring configuration, you can use the following steps to add a custom filter into the security filter chain.

Using XML configuration:

You can add the filter to the chain using the custom-filter tag and one of the filter alias like FORM_LOGIN_FILTER, BASIC_AUTH_FILTER to specify the position of your filter. For example, you can add your custom filter after FORM_LOGIN_FILTER as shown below:

<beans:bean id="customSpringScurityFilter" class="CustomSecurityFilter"/> 
  <custom-filter after="FORM_LOGIN_FILTER" ref="customSpringScurityFilter" /> 

Here are all attributes to specify exactly where to put your filter in the spring security filter chain:

after - specifies the filter immediately after which a custom filter will be added in the chain.

before - specified the filter before which your custom filter should be placed in the chain.

position - allows you to replace a standard filter in the explicit position with a custom security filter.

See here to see the full list of Spring security filter aliases:

Btw, if you are using Java Configuration then you can extend WebSecurityConfigurerAdapter and implement its's configure(HttpSecurity http) method to put your custom filter in the right place in the spring security filter chain.

10. Is security a cross-cutting concern? How is it implemented internally?
The cross-cutting concern is a concern that is applicable throughout the application and it affects the entire application. For example logging, security, and data transfer are the concerns that are needed in almost every module of an application, hence they are cross-cutting concerns. 

Different level of security is implemented differently like method level security is implemented using AOP. Spring Security framework also uses filters to implement security. 

You can further see Spring Security Fundamentals learn more about Authentication and Authorization on Spring Security. 

By the way, you would need a Pluralsight membership to join this course which costs around $29 per month or $299 per year (14% discount). I highly recommend this program to all Java developers as it provides instant access to more than 7000+ online courses to learn any tech skill. Alternatively, you can also use their 10-day-free-trail to watch this course for FREE.

11. What does @ and # is used for in Spring Expression Language (EL)?
The "@" symbol in Spring EL is used to reference a Spring Bean while the "#" symbol in Spring EL allows you to reference a parameter on the method you are securing. 

12. Which security annotations are allowed to use SpEL?
The @PreAuthorize is one of the most powerful annotations in Spring security which is allowed to use SpEL, but the old @Secured annotation is not allowed to use SpEL like you cannot write @Secured ("hasRole('ROLEADMIN')") but you can do @PreAuthorize("hasRole('ROLEADMIN')")

13. What is the security context?
The SecurityContext is an interface in the Spring Security framework which defines the minimum security information associated with the current thread of execution. It provides methods like the getAuthentication() which can be used to obtain the currently authenticated principal or an authentication request token. It returns null if no authentication information is available.  

You can further see my Spring Security Context article to learn more about it. 

spring security interview questions for java developers

2. Spring Security Authentication and Authorization Interview Questions

Now that we have seen many questions based upon Spring security architecture, spring-security filter chain, and other common stuff, it's time to look into another important aspect of Spring security, authentication, and authorization mechanism. In this section, we'll see some frequently asked questions from spring security authentication and authorization functionalities. 

14. What are authentication and authorization? Which must come first?
Authentication is a process to verify that the user is the one who he claims to be. It is generally implemented using a username and password. 

If a user enters the correct username and password then authentication is successful, otherwise, authentication failed. 

Authorization provides access control. For example, only the admin can see some pages in a web application. To implement that, the admin must have some admin-related permissions or roles. 

If a user becomes admin then those permissions are added to this profile. If you have access to a page it means you are authorized to that page or resources. Obviously, authorization comes after authentication because access can only be provided to genuine users. 

15. What is a Principal in Spring Security?
The principal is actually the currently logged in user. You can retrieve security context which is bound to the current thread and as such it's also bound to the current request and its session. The SecurityContextHolder.getContext() internally obtains the current SecurityContext implementation through a ThreadLocal variable.

Because a request is bound to a single thread this will get you the context of the current request.

16. Why do you need the intercept-url?
The intercept-url is needed to secure URLs in your Java web application using Spring security. It also defines some sort of authorization, I mean roll or access a user needs to see a page or URL. Most of the web applications using Spring Security only has a couple of intercept-urls because they only have very basic security requirements. 

You need to have unauthenticated or anonymous access to the login and login-error screens and usually some aspect of the public site, which can be intercepted in a few URL patterns. 

Then there's often an admin section for admin stuff like creating roles, users, or permissions, and then everything else is ROLE_USER.

Here is one of the examples of basic Spring security using intercept URL:

<http realm="Contacts Realm" use-expressions="false"> 
   <intercept-url pattern="/index.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY"/> 
   <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/> 
   <intercept-url pattern="/admin/*" access="ROLE_ADMIN"/> 
   <intercept-url pattern="/trade/*" access="ROLE_TRADER"/> 
   <intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN,ROLE_TRADER"/> 

You can see that index.jsp and admin.jsp is allowed to be accessed without authentication. Anything which has admin in URL required ROLE_ADMIN access and any URL with trade in it requires ROLE_TRADER access. 

Spring also allows expression-based access control from Spring 3.0 but it is not mandatory, though it gives you more power to implement complex access mechanisms. If you want to learn more about authentication and authorization on spring-security then you can also checkout OAuth 2.0 in the Spring Boot Applications course on Udemy. 

17. Why do you need method security?
Security is hard, you often need multiple levels of security to improve the chances to block circumvention attempts. Since method level security is directly coded inside the class, after the AOP augmentation, when you call the method, you'll always call the security check before.

Method level security is useful for two main reasons:

1. It provides  another layer of security (in addition to other layers)

2. In cases where it's more convenient or logical to have permissions at the method level consider a case where different users can perform the same "direct" actions (so client security isn't relevant). but in some cases, their action may trigger behavior you wish to limit - in this case, method level security may be a relevant solution. 

18. Is it enough to hide sections of my output (e.g. JSP-Page)? 
Not enough

19. What type of object is typically secured at the method level (think of its purpose, not its Java type).

20. In which order do you have to write multiple intercept-url's?
If you have multiple intercept URLs then you should write them more specific to less specific. Since intercept-url patterns are processed in the order in which they appear in the spring security configuration file, it's important that a URL must match with the right pattern. 

This becomes even more important when you have wildcards in your URL patterns.

In the following example, any incoming requests that do not match any of the specific patterns would be denied access since "<intercept-url pattern="/**" access="denyAll" />" is the last pattern to be matched.

<http use-expressions="true"> 
   <intercept-url pattern="/index.jsp" access="permitAll" /> 
   <intercept-url pattern="/secure/admin/**" access="hasRole('admin')" /> 
   <intercept-url pattern="/secure/**" access="isAuthenticated()" /> 
   <intercept-url pattern="/listAccounts.html" access="isAuthenticated()" /> 
   <intercept-url pattern="/post.html" access="hasAnyRole('supervisor','teller')" /> 
   <intercept-url pattern="/**" access="denyAll" /> 
   <form-login /> 

So the most specific patterns should come first, as they are tried in that order. One approach is to define a whitelist of URLs first then deny everything else.

21. What do @Secured and @RolesAllowed do? What is the difference between them?
Th @Secured annotation is used to define a list of security configuration attributes for business methods. You can specify the security requirements[roles/permission etc] on a method using the @Secured annotation and then only the user with those roles/permissions can invoke that method. 

If anyone tries to invoke a method and does not possess the required roles/permissions, an AccessDeniedException will be thrown. 

here is a simple example of @Secured annotation: 
public String showTrades() { 
   return "secure/trades"; 

The @Secured is coming from previous versions of Spring. It has a limitation in that it does not support Spring EL expressions. 

It's better to replace @Secured annotation with @PreAuthorize annotation which supports Spring EL. For example, the above code can be written using @PreAuthorize as follows: 

public String showTrades() { 
   return "secure/trades"; 

On the other hand, @RolesAllowed is a JSR 250 annotation, which specifies the security roles permitted to access a method or a couple of methods in an application. 

If you are not familiar with JSR 250, it's the objective to define common annotations for the Java platform, and if you want to learn more about essential Spring security annotations then you can pick a good course mention in these best spring security courses to start with. 

3. Spring Security Password Encoding questions

Now, let's see some Spring security interview questions on password security and protection related topics like hashing and salting, which is also important for Java developers. 

22. Does Spring Security support password hashing? What is salting?
One of the common problems of storing passwords on databases is their security. You just can't store passwords as plain text into your database because then anyone who has access to the database would have access to the password of every user. To solve this problem, encrypted passwords are stored in a database and this is known as password hashing.

In cryptography, a salt is random data that is combined with a password before password hashing. This makes a dictionary attack more difficult. This process is known as salting. The hashed version of the password is then stored in a database along with salt.

Btw, some hashing algorithms are not suitable for password hashing, if salt is too small or predictable it's possible to recover passwords by matching random words with salt then comparing the hashed version of output with the data stored in the database.

Yes, Spring Security includes password hashing out of the box. Since version 3.1, Spring Security automatically takes care of salting too. You can use PasswordEncoder implementation to implement password hashing in Spring security.

23. What is PasswordEncoder?
The PasswordEncoder is an interface in Spring security that provides password encoding or password hashing. It has two methods encode() to encode the raw password and matches() to verify the encoded password obtained from the database matches the submitted raw password after it too is encoded using the same salt and same hashing algorithm. 

24. Does order of intercept URL matters in Spring security config? (answer)
Yes, order of intercept URL matter in spring security config and if you have to define multiple URLs then you should define them in the order of most specific to least specific. Spring security matches every request and response to the intercept URLs in the same order they are declared. 

24. What are some implementations of PasswordEncoder in Spring Security?
Spring security provides several implementations based upon different hashing algorithms, which you can use in your application. 

The two important implementations of the new PasswordEncoder interface are BCryptPasswordEncoder and the confusingly named StandardPasswordEncoder based on SHA-256. 

The BCrypt implementation is the recommended one. There is also a NoOpPasswordEncoder which does no encoding. It's intended for unit testing only.

That's all about some of the frequently asked Spring Security Interview Questions. These questions are not only great for preparing for Spring job interviews but also for preparing for Spring Profesional Certifications. These questions are based upon essential spring security concepts, and a good knowledge of Spring security goes a long way in creating and maintaining a secure Java web and enterprise application. 

 Other Java and Spring articles you may like
  • 21 skills Java developers can learn (skills)
  • Spring Security Documentation (doc)
  • 10 Tips to become a better Java developer (tips)
  • 5 Spring Boot Annotations for full-stack Java developers (tutorial)
  • 5 Courses to learn Spring Cloud and Microservices (courses)
  • 5 Spring Boot Features Every Java Developer Should Know (features)
  • 10 Things Java Developer should learn (goals)
  • 10 Tools Java Developers use in their day-to-day life (tools)
  • Top 5 Books and Courses to learn RESTful Web Service (books)
  • 10 Pluralsight Courses to learn Spring in depth (courses)
  • 3 ways to change Tomcat port in Spring Boot (tutorial)
  • Top 5 Courses to learn Microservices in Java? (courses)
  • 5 courses to learn Spring Boot and Spring Cloud ( courses)
  • 10 Advanced Spring Boot Courses for Java Programmers (courses)
  • 10 Spring MVC annotations Java developers should learn (annotations)
  • 5 Course to Master Spring Boot online (courses)
  • 10 Courses to learn Spring Security with OAuth 2 (courses)
  • 3 Best Practices Java Programmers can learn from Spring (best practices)

Thanks for reading this article so far. If you found these Spring Security Interview questions useful then please share them with your colleagues and friends. If you have any questions or feedback then please drop a note. 

P. S. - If you are keen to learn more about Spring Security, OAuth2.0, and JWS then I suggest you join Eugen Periskov's Spring Security Certification class, one of the best online Spring Security courses currently available in the market. It's a bit expensive when you compare to Udemy courses but worth it. 

No comments :

Post a Comment