title: How to secure communication between 2 Spring Boot microservices using OAuth2?
body: <p>I'm learning about securing microservices with Basic Authentication and OAuth2 JWT Token Authentication. I implemented it using Basic Authentication and now I want to transform it in OAuth2 Authentication.</p>
  <p>This is the implementation for securing the communication between these 2 microservices using Basic Auth.</p>
  <p>Microservice 1 - REST API</p>
  <pre><code>@Configuration
  @Getter
  public class DemoApiConfiguration {
      @Value(&quot;${demo.api.credentials.username}&quot;)
      private String username;
  
      @Value(&quot;${demo.api.credentials.password}&quot;)
      private String password;
  }
  </code></pre>
  <p>SecurityConfigurer class:</p>
  <pre><code>@Configuration
  @RequiredArgsConstructor
  public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
      private final DemoApiConfiguration apiConfig;
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
                  .csrf().disable()
                  .authorizeRequests().anyRequest().authenticated()
                  .and()
                  .httpBasic();
      }
  
      @Bean
      public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
  
          UserDetails theUser = User.withUsername(apiConfig.getUsername())
                  .password(passwordEncoder.encode(apiConfig.getPassword())).roles(&quot;USER&quot;).build();
  
          InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
          userDetailsManager.createUser(theUser);
  
          return userDetailsManager;
      }
  
      @Bean
      public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
      }
  }
  </code></pre>
  <p>Controller class:</p>
  <pre><code>@RestController
  @RequestMapping(&quot;/rest/api/v1&quot;)
  public class HomeController {
  
      @GetMapping(&quot;/products&quot;)
      public String home() {
          return &quot;These are products!&quot;;
      }
  }
  </code></pre>
  <p>application.yml:</p>
  <pre><code>demo:
    api:
      credentials:
        username: ${demo_api_username:john}
        password: ${demo_api_password:test}
  </code></pre>
  <p>Microservice 2 - REST Consumer</p>
  <pre><code>@Configuration
  @Getter
  public class DemoApiConfiguration {
      @Value(&quot;${demo.api.credentials.username}&quot;)
      private String username;
  
      @Value(&quot;${demo.api.credentials.password}&quot;)
      private String password;
  
      @Value(&quot;${demo.api.credentials.basePath}&quot;)
      private String basePath;
  }
  </code></pre>
  <p>WebConfigurer class:</p>
  <pre><code>@Configuration
  @RequiredArgsConstructor
  public class WebConfigurer {
  
      private final DemoApiConfiguration apiConfig;
  
      @Bean
      public ApiClient restTemplate() {
          RestTemplate restTemplate = new RestTemplate();
          ApiClient apiClient = new ApiClient(restTemplate);
          apiClient.setBasePath(apiConfig.getBasePath());
  
          return apiClient;
      }
  
      public String getAuthorization() {
          return (!StringUtils.isEmpty(apiConfig.getUsername()) &amp;&amp;
                  !StringUtils.isEmpty(apiConfig.getPassword())) ?
                  &quot;Basic &quot; + Base64Utils.encodeToString((
                          apiConfig.getUsername() + &quot;:&quot; + apiConfig.getPassword())
                          .getBytes()) :
                  null;
      }
  }
  </code></pre>
  <p>ApiClient class:</p>
  <pre><code>@Getter
  @RequiredArgsConstructor
  @Slf4j
  public class ApiClient {
  
      private static final String AUTHORIZATION_HEADER = &quot;Authorization&quot;;
      private final RestTemplate restTemplate;
      private String basePath;
  
      public ApiClient setBasePath(String basePath) {
          this.basePath = basePath;
          return this;
      }
  
      public String invokeApi(String path, String credentials) {
          UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path);
  
          RequestEntity.BodyBuilder requestBuilder =
                  RequestEntity.method(HttpMethod.GET, builder.build().toUri());
  
          requestBuilder.contentType(MediaType.APPLICATION_JSON);
          requestBuilder.header(AUTHORIZATION_HEADER, credentials);
  
          RequestEntity&lt;Object&gt; requestEntity = requestBuilder.body(null);
  
          return restTemplate
                  .exchange(requestEntity, String.class).getBody();
      }
  }
  </code></pre>
  <p>ConsumeController class:</p>
  <pre><code>@RestController
  @RequiredArgsConstructor
  public class ConsumeController {
  
      private static final String PATH = &quot;/rest/api/v1/products&quot;;
      private final WebConfigurer webConfigurer;
      private final ApiClient apiClient;
  
      @GetMapping(value = &quot;/products-client&quot;)
      public String getProductList() {
  
          return apiClient.invokeApi(PATH, webConfigurer.getAuthorization());
      }
  }
  </code></pre>
  <p>application.yml:</p>
  <pre><code>server:
    port: 8090
  
  demo:
    api:
      credentials:
        username: ${demo_api_username:john}
        password: ${demo_api_password:test}
        basePath: ${demo_api_path:http://localhost:8080}
  </code></pre>
  <p>So the first microservice is a REST API and the second microservice is a REST consumer and the communication is secured using Basic Auth.</p>
  <p>Now I want to implement using OAuth2, and I want to ask you how can I secure the communication using OAuth2? So I want to add another endpoint like &quot;/access-token&quot;, and the client first will do a request at this endpoint with username and password and will get a jwt token. After that will do a request for &quot;/products&quot; endpoint with Authorization header using this jwt token. Can you help me to do this kind of implementation? Thank you!</p>