Spring Security Interview Questions (2021) | CodeUsingJava








Spring Security Interview Questions

In this post we will look at Spring Security Interview questions. Examples are provided with explanation.
Spring Security Interview Questions
  1. What is Spring Security?
  2. What are the features of using Spring Security?
  3. What is so special about FilterChainProxy?
  4. Define the inner beans in Spring?
  5. What do you mean by public key feature?
  6. How to refresh Expired JWT Token?
  7. How to implement Spring Boot + JWT?
  8. How to implement Spring Boot + JWT + MySQL?
  9. What is Hashicorp Vault and how to implement it using Spring Boot?
  10. What is DelegatingFilterProxy in Spring Security?
  11. What is Spring Security OAuth2?
  12. What is Digest Authentication?
  13. What are Authorities in Authentication object?
  14. What Is A Security Context?
  15. What is ProviderManager in Spring Security?
  16. What is OAuth2 Authorization code grant type?
  17. What are Runners in Spring Security?
  18. What are All Security Layers In Spring Security Framework?
  19. What Are Access Controls In Spring Security?
  20. Name the modules of the Spring framework?
  21. What is the difference between ROLE_USER and ROLE_ANONYMOUS in a Spring intercept url configuration?
  22. What is Hashing in Spring Security?
  23. What is Actuator in Spring Security?
  24. How is Security mechanism implemented using Spring?
  25. What are some predefined filters used by Spring Security? What are their functions and in which order they occurred?
  26. Why do you need the intercept-url?
  27. How to get the current logged-in username in Spring Security?
  28. What happens if we don't have an SSL?
  29. How is a Principal defined?
  30. What is View Resolver in Spring?
  31. What is Salting and why do we use the process of Salting?
  32. Difference between Role and GrantedAuthority in Spring Security?

What is Spring Security?

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.
Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements


What are the features of using Spring Security?

  • Comprehensive and extensible support for both Authentication and Authorization.
  • Protection against attacks like session fixation, clickjacking, cross site request forgery, etc.
  • Servlet API integration.
  • Optional integration with Spring Web MVC.

How to implement security for Spring Boot + MySQL project?

Spring Security is one of the most important framework used for making enterprise applications. It provides some of the important features which includes user authentication i.e.who you are and authorization i.e. are you authorized to fetch a particular request.
Springsecurity intro
The mysql default schema can be defined as follows- The username in the User class acts as a foreign key for the Authority class.
Mysql default schema

Spring Boot + Security + MySQL Hello World Example(2021)

What is so special about FilterChainProxy?

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

Define the inner beans in Spring?

Inner Beans in the Spring means beans that are defined within the scope of another bean whenever a bean is used for only one particular property. It's advise to declare it as an inner bean.It supported in setter injection and constructor injection.

What do you mean by public key feature?

PKI refers to a communal ecosystem of roles, responsibilities, policies, and events for issuing, managing, and revoking digital certificates. The PKI ecosystem ensures the safe and private swap of responsive electronic information between known and unknown parties over untrusted networks.

How to refresh Expired JWT Token


The access token contains all the information of the server in an encrypted form. Generally in an enterprise application, Ensuring that the security of the application is preserved, there is an expiration time after which the access token is not in any use.
So now the user need to validate himself again. But By using the refresh token, the user can directly get the new access token which will help user to fetch all the API's for which he is authorised. This can be diagrammatically explained as follows-

Introduction
Spring Boot + JSON Web Token (JWT) Refresh Token(2021) Example

How to implement Spring Boot + JWT?

As we have already discussed the basic introduction and structure of JWT so here, In this tutorial we will be implementing a hello world example using JSON Web Token.
Here in our example, JWT spring security is configured. First the user will do the validate by passing the username and password.
Then a JSON Web Token is returned in response. Now any other request can be validated with the help of JSON Web Token. The steps can be diagrammatically represented as follows-
jwt work flow
Spring Boot + JSON Web Token (JWT)(2021) Hello World Example

How to implement Spring Boot + JWT + MySQL?

So here, in this tutorial we will be implementing a hello world example using JSON Web Token using MySQL database to store the user credentials.
Here in our example, JWT spring security is configured. First the user will do the validate by passing the username and password to the database.
Then a JSON Web Token is returned in response. Now any other request can be validated with the help of JSON Web Token.
The steps can be diagrammatically represented as follows-
jwt work flow
Spring Boot + JSON Web Token (JWT)+ MySQL Hello World Example

What is Hashicorp Vault and how to implement it using Spring Boot?

In this tutorial we will be implementing a Spring Boot with Vault Integration. While dealing with the microservices architecture. it is essential to have a management of the configuration. There is a need to have a centralised configuration where the sensitive data can be kept safe. Here comes the need of integration of Vault.
Spring cloud Vault helps to access the secrets that are stored in it.
Some of the advantages of using Vault includes- Secure and Secret Storage, Dynamic Secrets, Encryption of Data, Revocating the tree of secrets and many more.
introduction
Spring Boot + Vault Integration(2021) Example

What is DelegatingFilterProxy in Spring Security?

DelegatingFilterProxy is the entry point of Spring Security in a Java web application. Spring Security is based on the concept of Servlet filters. DelegatingFilterProxy

Spring Security Configuration

  • DigestAuthenticationFilter processes Digest Authorization Headers of the HTTP request , placing the result into the SecurityContextHolder.
  • If authentication is successful, the resulting Authentication object will be put in the SecurityContextHolder.
  • If authentication fails, an implementation of AuthenticationEntryPoint will be called. This will always be DigestAuthenticationEntryPoint, which will request the user to authenticate by Digest Authentication again.
  • DigestAuthenticationFilter includes an entry point and UserDetailsService consists of user information such as username , password, activation information, etc.
  • For digest authentication, DigestAuthenticationEntryPoint requires an authentication entry point. Entry point needs a key and a realm.

What is Spring Security OAuth2?

  • Spring security provides comprehensive security services for j2ee-based enterprise software applications.Oauth is an open-authorization protocol that allows accessing resources of the resource owner by enabling the client applications on http services, such as gmail, github, etc.
  • 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.

What is Digest Authentication?

Digest authentication is one of the agreed-upon methods a web server can use to negotiate credentials, such as username or password, with a user's web browser. This can be used to confirm the identity of a user before sending sensitive information, such as online banking transaction history. It applies a hash function to the username and password before sending them over the network. In contrast, basic access authentication uses the easily reversible Base64 encoding instead of hashing, making it non-secure unless used in conjunction with TLS.

What are Authorities in Authentication object?

Spring Security provides a variety of options for performing authentication. These follow a simple contract - an Authentication request is processed by an AuthenticationProvider and a fully authenticated object with full credentials is returned.
Authorities

What Is A Security Context?

Security context in Spring Security includes details of the principal currently using the application. Security context is always available to methods in the same thread of execution, even if the security context is not explicitly passed around as an argument to those methods.

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

What is OAuth2 Authorization code grant type?

The Authorization Code Grant Type is probably the most common of the OAuth 2.0 grant types that you'll encounter. It is used by both web apps and native apps to get an access token after a user authorizes an app.

What are Runners in Spring Security?

Application Runner and Command Line Runner interfaces lets you to execute the code after the Spring Boot application is started. You can use these interfaces to perform any actions immediately after the application has started.
  • Application Runner- Application Runner is an interface used to execute the code after the Spring Boot application started. The example given below shows how to implement the Application Runner interface on the main class file.
    package com.tutorialspoint.demo;
    
    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class DemoApplication implements ApplicationRunner {
       public static void main(String[] args) {
          SpringApplication.run(DemoApplication.class, args);
       }
       @Override
       public void run(ApplicationArguments arg0) throws Exception {
          System.out.println("Hello People from Application Runner");
       }
    }
    
  • Command Line Runner- Command Line Runner is an interface. It is used to execute the code after the Spring Boot application started.The example given below shows how to implement the Command Line Runner interface on the main class file.
    package com.tutorialspoint.demo;
    
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class DemoApplication implements CommandLineRunner {
       public static void main(String[] args) {
          SpringApplication.run(DemoApplication.class, args);
       }
       @Override
       public void run(String... arg0) throws Exception {
          System.out.println("Hello people from Command Line Runner");
       }
    }
    

What are All Security Layers In Spring Security Framework?

  • Authentication
  • Web request security
  • Service layer and domain object security

Why should we use JWT Tokens?

Features of JWT are below:
  • Information Exchange - JWT is good and secure in exchanging information between parties as they can be signed.
  • Easier to process - It used at internet scale, as it is easier to process on users device.
  • More compact - JWT is a smaller token than SAML token, this makes JWT a good choice to be passed in HTML and HTTP environments.
  • Authentication - ID token is always JWT token.
  • Authorization - JWT is widely used for authorization because of the overhead of the format and its ability to easily be used across different domains.
Why use JSON Web Token

How to implement Security for Spring Boot + Swagger project

The configuration class for the Web Security Configuration is as follows-
The @EnableWebSecurity is used to configure Spring Security in our application.
The url for the Swagger must be configured to be permitted by all the users.
We have used BCryptPasswordEncoder to encode the password and used inMemoryAuthentication to store user credentials. The password stored is 123. The description of these terms can be seen in previous SpringWebSecurity article.
Various Security Schemes can be provided by the OpenApi. We can define several components like Scheme, type , header etc. in our application.

package com.codeusingjava.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.security.SecurityScheme;


@EnableWebSecurity   
@SecurityScheme(name="codeusingjava", scheme="basic", type=SecuritySchemeType.HTTP, in=SecuritySchemeIn.HEADER)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication()
		.withUser("nj")
		.password("{bcrypt}$2a$10$BagghBQvnxcVuhHyXc9g9.fM6s109FakmyF4tPAoOMRkjqKsg1xl.") //123
		.authorities("ADMIN");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
		
		.antMatchers("/swagger-ui/**","/v3/api-docs/**").permitAll()
		.anyRequest().authenticated()
		.and().httpBasic();
		http.csrf().disable();
	}
}

Spring Boot + Swagger 3(OpenAPI) + Web Security Example(2021)

What Are Access Controls In Spring Security?

  • The files in the directory "/secure" should only be visible to authenticated users.
  • The files in the directory "/secure/extreme" should only be visible to Supervisors.
  • Withdrawal and deposits can be made only by Tellers and Supervisors.
  • Overdraft limit for an account can be exceeded only by Supervisors.

How to implement Spring Boot + JWT?

Spring Boot + JSON Web Token (JWT)(2021) Hello World Example

Name the modules of the Spring framework?

The modules of the Spring framework are:
  • Test
  • Data Access
  • AOP
  • Web
Spring framework

What is the difference between ROLE_USER and ROLE_ANONYMOUS in a Spring intercept url configuration?

  • ROLE_ANONYMOUS is the default role assigned to an unauthenticated (anonymous) user when a configuration uses Spring Security's "anonymous authentication" filter . This is enabled by default. However, it is probably clearer if you use the expression isAnonymous() instead, which has the same meaning.
  • ROLE_USER has no meaning unless you assign this role to your users when they are authenticated (you are in charge of loading the roles (authorities) for an authenticated user). It isn't a name that is built in to Spring Security's infrastructure. In the given example, presumably that role is assigned to an authenticated user.

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

What is Actuator in Spring Security?

Spring Boot Actuator provides secured endpoints for monitoring and managing your Spring Boot application. By default, all actuator endpoints are secured. In this chapter, you will learn in detail about how to enable Spring Boot actuator to your application.

How is Security mechanism implemented using Spring?

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements. Spring makes use of the DelegatingFilterProxy for implementing security mechanisms. It is a Proxy for standard Servlet Filter, delegating to a Spring-managed bean that implements the Filter interface.
Spring Boot + Security Hello World Example(2021)