Search Tutorials


Top Spring Security Interview Questions | JavaInUse

Spring Security Interview Questions.


In this post we will look at Spring Security Interview questions. Examples are provided with explanation.


  1. Explain Spring Security Architecture using Spring Boot?
  2. What is OAuth2 Authorization code grant type? How to implement it using Spring Boot Security?
  3. Using Spring Boot Security how to refresh expired JSON Web Token?
  4. What is JWT ? How to implement it using Spring Boot Security
  5. What is OAuth2 Client Credentials Grant? How to implement it using Spring Boot Security
  6. What is OAuth2 Password Grant? How to implement it using Spring Boot Security
  7. How to configure Spring Security using Spring Boot?
  8. How to create Custom Login Page using Spring Boot Security?
  9. How to do authentication against database tables using Spring Boot Security?
  10. How to configure Spring Security with in-memory configuration?
  11. What is the use of Spring Boot Security AuthenticationHandler class?
  12. What is the difference between ROLE_USER and ROLE_ANONYMOUS in a Spring intercept url configuration?
  13. How to configure DelegatingFilterProxy?
  14. How to configure Spring Security using Spring MVC?


Explain Spring Security Architecture using Spring Boot?

Let us understand how Spring Security Works.

Understand Spring Security Architecture and implement Spring Boot Security

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. Its the starting point in the springSecurityFilterChain which instantiates the Spring Security filters according to the Spring configuration
Some of the features of Spring Security are
  • 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

What is OAuth2 Authorization code grant type? How to implement it using Spring Boot Security?

OAuth (Open Authorization) is a simple way to publish and interact with protected data.
It is an open standard for token-based authentication and authorization on the Internet. It allows an end user's account information to be used by third-party services, such as Facebook, without exposing the user's password.
The OAuth specification describes five grants for acquiring an access token:
  • Authorization code grant
  • Implicit grant
  • Resource owner credentials grant
  • Client credentials grant
  • Refresh token grant
Consider the use case of Quora. Go to Quora.com.
If you are a new user you need to signup. You can signup using google or facebook account. When doing so you are authorizing Google or Facebook to allow quora to access you profile info with Quora. This authorizing is done using OAuth. Here you have in no way shared your credentials with Quora.
Understanding What Is OAuth2
Spring Boot OAuth2 Part 1 - Getting The Authorization Code
Spring Boot OAuth2 Part 2 - Getting The Access Token And Using it to fetch data.

Using Spring Boot Security how to refresh expired JSON Web Token?

In previous tutorial we had implemented Spring Boot + JWT Example. We had also covered the topic of JWT Expiration. We had implemented the solution such that if the JWT has expired then the user gets JWTExpiredException.
Suppose our requirement is such that if the token has expired, still the user should be allowed to access the system if the token is valid. That is the token should be refreshed or a new valid token should be provided.
We will be working on a solution where if the user he receives JWT expired exception, then he can call another API with the expired token. A new token will then provided to the user which he can use for future interactions. Previously we had implemented an example for programmatically consuming the JWT secure API using Spring RestTemplate. We will be testing this refresh Token generation API both using Postman as well as the Spring RestTemplate.

What is JWT ? How to implement it using Spring Boot Security?

For better understanding we will be developing the project in stages
  • Develop a Spring Boot Application to expose a Simple REST GET API with mapping /hello.
  • Configure Spring Security for JWT. Expose REST POST API with mapping /authenticate using which User will get a valid JSON Web Token. And then allow the user access to the api /hello only if it has a valid token
    Spring Boot JWT Workflow
What is JWT(JSON Web Token)
Spring Boot +JSON Web Token(JWT) Hello World Example




What is OAuth2 Client Credentials Grant? How to implement it using Spring Boot Security?

The Client Credentials Grant involves machine to machine authentication. In case of Client credentials grant type the user has no role to play. As previously stated it is machine to machine communication. This is typically used by clients to access resources about themselves rather than to access a user's resources.
Spring Boot OAuth2 Client Credentials Grant
This type of Authentication does not involve any end-user. Unlike Authorization Grant where the end user had to authenticate himself using Authorization Server like Gmail, here the machine it self authenticates itself to access a protected resource.
Spring Boot + OAuth 2 Client Credentials Grant - Hello World Example.

What is OAuth2 Password Grant? How to implement it using Spring Boot Security

In case of Password grant type the user triggers the client to get some resource. While doing so it passes the username and password to the client. The client then communicates with the authorization server using the provided username, password and also its own clientId and clientSecret to get the access token. Using this access token it then gets the required resource from the resource server.
Spring Boot OAuth2 Password Grant
The real life example of Password grant will be you doing a login to you facebook account using its mobile application. Here the user will have to specify the facebook credentials to the app. Also the app will be having its own client id and client secret.
Spring Boot OAuth2 Facebook Password Grant
Spring Boot + OAuth 2 Password Grant - Hello World Example.

How to configure Spring Security using Spring Boot?

Spring Boot + Simple Security Configuration

How to use Form Login Authentication using Spring Boot

We make use of Spring Boot Security to get default login page and authentication users.
	@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/welcome")
            .hasAnyRole("USER", "ADMIN").antMatchers("/getEmployees").hasAnyRole("USER", "ADMIN")
            .antMatchers("/addNewEmployee").hasAnyRole("ADMIN").anyRequest().authenticated().and().formLogin()
            .permitAll().and().logout().permitAll();

        http.csrf().disable();
    }
Spring Boot Form Security Login Hello World Example

How to create Custom Login Page using Spring Boot Security?

We can create our own custom login page and use it for authentication.
    @Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/welcome").hasAnyRole("USER", "ADMIN")
				.antMatchers("/getEmployees").hasAnyRole("USER", "ADMIN").antMatchers("/addNewEmployee")
				.hasAnyRole("ADMIN").anyRequest().authenticated()
				.and().formLogin().loginPage("/login").permitAll()
				.and().logout().permitAll();

		http.csrf().disable();
	}
Spring Boot Security - Custom Login Page Example

How to do authentication against database tables using Spring Boot Security?

Spring Authentication using username, password and authorization using roles can be done using either
  • In Memory Configuration -
    	@Autowired
        public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
            authenticationMgr.inMemoryAuthentication().withUser("employee").password("employee")
                .authorities("ROLE_USER").and().withUser("javainuse").password("javainuse")
                .authorities("ROLE_USER", "ROLE_ADMIN");
        }
    				 
    Spring Boot Security In Memory Authentication Example
  • Database Authentication-
    	@Autowired
        public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
            auth.jdbcAuthentication().dataSource(dataSource);
        }
    
    Spring Boot Security - JDBC Authentication Example

How to configure Spring Security with in-memory configuration?

    @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) 
  throws Exception {
    auth.inMemoryAuthentication()
      .withUser("user").password("password").roles("USER")
      .and()
      .withUser("admin").password("password").roles("USER", "ADMIN");


What is the use of Spring Boot Security AuthenticationHandler class?

In some scenarios we might want to redirect different users to different pages depending on the roles assigned to the users.
For example we might want users with role USER to be redirected to the welcome page, while users with role ADMIN to be redirected to the add employee page.
We will be making use of the AuthenticationSuccessHandler.
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/welcome").hasAnyRole("USER", "ADMIN")
				.antMatchers("/getEmployees").hasAnyRole("USER", "ADMIN").antMatchers("/addNewEmployee")
				.hasAnyRole("ADMIN").anyRequest().authenticated()
				.and().formLogin().successHandler(successHandler)
				.loginPage("/login").permitAll().and().logout().permitAll();

		http.csrf().disable();
	}
Spring Boot Form Security Login Hello World Example

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.


How to configure DelegatingFilterProxy?

In the web.xml we add the DelegatingFilterProxy which is delegating proxy to automatically intercept a URL with a particular pattern to apply spring security.
    <filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

How to configure Spring Security using Spring MVC?

Simple Spring Security example using Basic Authentication Provider

What's the difference between @Secured and @PreAuthorize in spring security

if you wanted to do something like access the method only if the user has Role1 and Role2 the you would have to use @PreAuthorize @PreAuthorize("hasRole('ROLE_role1') and hasRole('ROLE_role2')") Using @Secured({"role1", "role2"}) is treated as an OR



See Also

Spring Boot Interview Questions Apache Camel Interview Questions Drools Interview Questions Java 8 Interview Questions Enterprise Service Bus- ESB Interview Questions. JBoss Fuse Interview Questions Top ElasticSearch frequently asked interview questions