Spring Security Interview Questions (2024)


Spring Security Interview Questions (2024)

In this post, questions of Spring Security with JWT and OAuth Interviews will be answered for Experienced and Freshers. We're trying to share our experience and learn how to help you make progress in your career.

Spring Boot Security Interview Questions:

  1. Spring Security Interview Questions
  2. OAuth2.0 Interview Questions
  3. JWT Interview Questions
  4. SAML Interview Questions
  5. LDAP Interview Questions

Q: What is Spring Security?
Ans:

Spring Security is a framework that focuses on providing authentication, authorization, and protection against common attacks.

Spring Security enables a programmer to impose security restrictions to Spring-framework-based Web applications through JEE components. In short, it is a library that can be used, extended to customize as per the programmer's needs.

Q: Why Security is needed in application?
Ans:

Security of applications is very important because now a days applications are often accessible over multiple networks and connected to the cloud, growing vulnerabilities to security threats and breaches.

Q: What is Delegating Filter Proxy?
Ans:

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:

  • 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

Q: What is Security Context and Security Context Holder in Spring Security?
Ans:

The SecurityContext and SecurityContextHolder are two fundamental classes of Spring Security. The SecurityContext is used to store the details of the currently authenticated user, also known as a principle.

Q: What is Basic Authentication?
Ans:

Basic Authentication is a way to provide authentication by passing username and password as part of our request, using HTTP [Authorization] header to allows user to access the resource.

Syntax of basic Authentication

Value = username:password
Encoded Value =  base64(Value)
Authorization Value = Basic <Encoded Value>
//Example: Authorization: Basic VGVzdFVzZXI6dGVzdDEyMw==
//Decode it'll give back the original username:password TestUser:test123

Q: How to implement Spring Boot + Basic Authentication?
Ans:

You can implement Basic Authentication by following steps:

  • Create Spring boot project from Spring Initializr
  • Add spring-boot-starter-security maven dependency in pom.xml.
  • Configure the user and password in application.yml
  • Configure Spring Security by extending WebSecurityConfigurerAdapter to enable the basic authentication for our REST API. Override configure method, to use HTTP basic authentication.
  • Create some simple rest end point to test the basic authentication, which can configure in the above step.
  • Test above created Rest end point.
Refer Spring Boot Basic Authentication Example implemented as per above steps.

Checkout our related posts :

Q: What are the drawbacks of using Basic Authentication?
Ans:

  • Basic Authentication uses base64 encoding(not encryption) for generating cryptographic string which contains the information of username and password. Basic Authentication is not secured, as it can be easily decoded as shown below.
  • Decode credential: You can see, if we copy Authorization: Basic VGVzdFVzZXI6dGVzdDEyMw== from output generated from the
  • Using Spring Boot Basic Authentication Example, we have generated below base64 Authorization hearder, as shown below we can decode the credential, which will give credential in the form of user:password, which is not secured.
  • There is no explicit HTTP basic authentication logout. You must exit the browser to force logout.

Q: What is Digest Authentication?
Ans:

Digest Authentication communicates credentials in an encrypted form by applying a hash function to : the username, the password, the nonce value provided by a server, the HTTP method and the requested URI.

Q: Why to use Digest Authentication over Basic Authentication?
Ans:

  • Basic Authentication uses base64 encoding(not encryption) for generating cryptographic string which contains the information of username and password. Basic Authentication is not secured, as it can be easily decoded as shown below.

    Syntax of basic Authentication

    Value = username:password
    Encoded Value =  base64(Value)
    Authorization Value = Basic <Encoded Value>
    //Example: Authorization: Basic VGVzdFVzZXI6dGVzdDEyMw==
    //Decode it'll give back the original username:password TestUser:test123

    Digest Authentication uses the hashing technique to generate the cryptographic result, which is more complex.

    RFC 2617 - Digest Access Authentication Syntax

    Hash1=MD5(username:realm:password)
    Hash2=MD5(method:digestURI)
    response=MD5(Hash1:nonce:nonceCount:cnonce:qop:Hash2)
    
    //Example , this got generated by running this example
    Authorization: Digest username="TestAdmin", realm="admin-digest-realm",
    nonce="MTYwMDEwMTUyMDM4OToxM2M1Y2I4MGFjMjk4OGI1ODQzZjc3NDUzOGFlMjZjYw==",
    uri="/admin/hello?name=User", response="2f080edbec53be2bdf3853d477e4a543",
    qop=auth, nc=00000002, cnonce="11ecd9bf947dbcf4"
    

Q: How to implement Spring Boot + Digest Authentication?
Ans:

You can implement Digest Authentication by following steps:

  • Create Spring boot project from Spring Initializr
  • Add spring-boot-starter-security maven dependency in pom.xml.
  • Create Spring Security Configuration class by extending WebSecurityConfigurerAdapter.
  • Configure the user and password in Spring Security Configuration Class.
  • Configure DigestAuthenticationFilter in Spring Security Configuration Class, and inject userDetailsService and DigestAuthenticationEntryPoint
  • Create some simple rest end point to test the basic authentication, which can configure in the above step.
  • Test above created Rest end point.
Refer Digest Authentication Example implemented as per above steps.

Q: How to get the current logged-in username in Spring Security?
Ans:

The object returned by getContext() is an instance of the SecurityContext interface. Normally, the getPrincipal() method returns the UserDetails object in Spring Security that contains all the details of the user that is currently logged in.


Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
  String logged_in_username = ((UserDetails)principal).getUsername();
} else {
  String logged_in_username = principal.toString();
}

Q: What is ssl and why it is used?
Ans:

Secure Sockets Layer (SSL) was the most commonly used cryptographic protocol to provide security over internet communications.

SSL provides a secure channel between two machines or devices running over the internet or an internal network. A common example is when SSL is used to secure/protect communication between a web browser and a web server. This changes the address of the website from HTTP to HTTPS, basically 'S' stands for 'Secure'.

Q: How do I know a Website is Secure with SSL?
Ans:

Take a look at the URL of the website. If it starts with "https" instead of "http" it means that the site is protected using an SSL certificate (S stands for secure). SSL certificates secure all of your data as it is transferred from your browser to the web server.

Q: Why do we need SSL certificate for website?
Ans:

The SSL certificate encrypts data that goes back and forth from the user's device to the target website. Any time a user enters information on your site, SSL ensures that they can navigate securely from their browser to your web server.

Q: What happens if we don't have an SSL?
Ans:

If you do not have an SSL certificate, a secure connection cannot be established, which means that your website information will not be digitally connected to a cryptographic key. The SSL Certificate includes the following information:

  • Name of the holder
  • Serial number
  • Expiration date

Q: Can we create our own SSl Certificate to enable HTTPS for website?
Ans:

Yes, we can create SSL certificate by using keytool. SSL certificates have a key pair: a public and a private key. These keys work together to establish an encrypted connection.

Follow the below steps to enable HTTPS for website:

  1. Generate an SSL certificate in a keystore.
  2. Verify the keystore content.
  3. Convert a JKS keystore into PKCS12.
  4. Configuring/Enable SSL in Spring Boot.
  5. Configure Spring Security to require HTTPS requests.
Refer Enable https (http+ssl) Example implemented as per above steps.

Q: What is PKCS12?
Ans:

PKCS12 Public Key Cryptographic Standards is a password-protected format that can include many certificates and keys, it is a format mainly used in the industry.

Q: What is JKS?
Ans:

Java KeyStore is identical to PKCS12, it is a proprietary format limited to the Java environment.

Refer Example of generating Keystore and integrating with Spring Boot Application

Q: Difference between a Java Keystore JKS and PKCS12?
Ans:

The default keystore format used was JKS until Java 8. However, now since Java 9, PKCS12 has been the default keystore format.
Another main difference between JKS and PKCS12 is that JKS is a Java-specific format, while PKCS12 stores encrypted private keys and certificates in a standardized and language-neutral way.

Q: What is AbstractSecurityInterceptor in Spring Security?
Ans:

The AbstractSecurityInterceptor in Spring Security handles the initial authorization of an incoming request.

There are two concrete implementations of the AbstractSecurityInterceptor:

  1. FilterSecurityInterceptor
    The Spring Security filter chain's default filter. All authenticated user requests will be authorised by the FilterSecurityInterceptor.
  2. MethodSecurityInterceptor
    This is required for method level security to be implemented. It enables us to apply security to our programme at the method level.

What is Spring Boot Method-Level Security?

The @PreAuthorize annotation is used on controller methods to implement method-level security. This annotation comprises a snippet of Spring Expression Language (SpEL) that is evaluated to determine whether the request should be authenticated.

Refer implementation of Spring Boot Method Security with PreAuthorize Example

Q: What is difference of using @PreAuthorize and @Secured in Spring Security?
Ans:

@PreAuthorize annotation is used to check for authorization before executing the method.

We could alternatively use the @Secured annotation in spring to handle method-level security, however it has several limitations, such as

  1. We cannot have several conditions with the @Secured annotation, i.e. the roles cannot be coupled with an AND/OR condition.
  2. Spring expression language is not supported by the @Secured annotation.

Q: What is the difference between hasRole() and hasAuthority()?
Ans:

Spring roles are authorities with the ROLE_prefix. Another thing to understand of it is that roles are meant for broad sets of permissions, whereas authorities are meant for finer-grained management. However, that is only one possible usage. The developer is in charge of the actual implementation. In this tutorial, authorities are used to map to authorization groups.


@PreAuthorize("hasAuthority('Admin')")
@RequestMapping("/fetch-users")
@ResponseBody
public String protectedUserPage() {
    return "TechGeekNext User";
}

------------------------------------------

@PreAuthorize("hasRole('admin')")
@RequestMapping("/fetch-users")
public String protectedUserPage() {
    return "TechGeekNext User";
}

The crucial thing to remember is that in order to use hasRole(), the authority name in the claim must begin with ROLE_. You might, for example, use hasRole('ADMIN') if you created a ROLE ADMIN group and added your user to it.

Q: What is difference between Spring Security's @PreAuthorize and HttpSecurity?
Ans:

  1. The first distinction is small, but it is important to note. Before controller mapping occurs, the HttpSecurity function rejects the request in a web request filter. The @PreAuthorize assessment, on the other hand, occurs later, directly before the controller method is executed. This means that HttpSecurity configuration is done before @PreAuthorize.
  2. Second, HttpSecurity is associated with URL endpoints, whereas @PreAuthorize is associated with controller methods and is located within the code next to the controller definitions.
  3. The use of SpEL (Spring Expression Language ) is another advantage that @PreAuthorize has over HttpSecurity.

Q: How to enable Method-level Security for Spring?
Ans:

The @PreAuthorize annotation is enabled by the @EnableGlobalMethodSecurity(prePostEnabled = true) annotation.

@Component
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
.......
.......
}

Refer for complete implementation of Spring Boot Method Security with PreAuthorize Example

Q: How to use Authorization Based On OAuth 2.0 with PreAuthorize?
Ans:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    protected void configure(final HttpSecurity http) throws Exception {
        http.antMatcher("/**")
            .authorizeRequests()
            .antMatchers("/").permitAll()
            .anyRequest().authenticated()
            //.and().formLogin();   // <-- Without OAUTH 
            .and().oauth2Login();  // <-- With OAUTH
    }
}

Q: Which open source tools are available for Oauth 2.0 /SAML/ OpenID Connect based SSO?
Ans:

Keycloak is a modern application and service-oriented open source Identity and Access Management system. Single-Sign-On (SSO), Identity Brokering and Social Login, User Federation, Client Adapters, an Admin Console, and an Account Management Console are some of the features offered by Keycloak.

It works with a variety of protocols, including Oauth 2.0, SAML 2.0 and OpenID Connect. User credentials can also be stored locally or via an LDAP or Kerberos backend.

When a user logs in successfully with Keycloak, they are given a token, which is saved as a cookie in the browser, and they are automatically sent back to the service they were trying to access. This token usually includes a username as well as information about the user's permissions.

Refer Spring Boot Keycloak SSO Example to understand it's implementation.








Recommendation for Top Popular Post :