WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Framework · Expert · question 67 of 100

How can you integrate Spring Security with OAuth2 and OpenID Connect for securing RESTful APIs?

📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

Spring Security provides comprehensive support for OAuth2 and OpenID Connect-based security solutions.

Here are the steps on how to integrate Spring Security with OAuth2 and OpenID Connect for securing RESTful APIs:

1. Add the required dependencies - The first step is to add the following dependencies to your Spring Boot application:

implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.security:spring-security-oauth2-client'
implementation 'org.springframework.security:spring-security-oauth2-jose'

2. Configure the OAuth2 client - After adding the dependencies, configure the OAuth2 client by specifying the authorization server’s details in the ‘application.yml‘ or ‘application.properties‘ file. For example:

spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            clientId: <client_id>
            clientSecret: <client_secret>
            scope:
              - openid
              - profile
              - email
        provider:
          okta:
            issuerUri: https://dev-123456.okta.com/oauth2/default

3. Configure the security filter chain - The next step is to configure Spring Security’s filter chain to include the OAuth2 security filter. This filter intercepts requests and validates the OAuth2 access token before allowing the request to proceed. This can be done using the ‘WebSecurityConfigurerAdapter‘ class, for example:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests(authorizeRequests ->
            authorizeRequests.antMatchers("/api/**").authenticated())
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
   }
}

In this example, any requests to ‘/api/**‘ paths are authenticated, and the ‘OAuth2ResourceServerConfigurer‘ is used to configure JWT-based security for the OAuth2 resource server.

4. Secure your REST endpoints - Finally, secure your RESTful endpoints by adding the ‘@PreAuthorize‘ annotation to your REST controller methods. For example:

@RestController
@RequestMapping("/api")
public class MyRestController {

   @GetMapping("/resource")
   @PreAuthorize("hasAuthority('SCOPE_profile')")
   public String getResource() {
      return "Hello, World!";
   }
}

Here, the ‘@PreAuthorize‘ annotation is used to restrict access to the ‘/api/resource‘ endpoint to users with the ‘SCOPE_profile‘ authority in their access token.

In summary, integrating Spring Security with OAuth2 and OpenID Connect for securing RESTful APIs involves adding the necessary dependencies, configuring the OAuth2 client, configuring the security filter chain, and securing your REST endpoints using the ‘@PreAuthorize‘ annotation.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Framework interview — then scores it.
📞 Practice Spring Framework — free 15 min
📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

All 100 Spring Framework questions · All topics