Spring WebClient OAuth2 Integration for Spring Web (Servlet)

Last Updated:  August 27, 2021 | Published: November 16, 2019

In one of my previous blog posts, I gave an example of how to configure the Spring WebClient for OAuth2 using Spring WebFlux. As most of the applications today are using Spring Web (Tomcat) and are not fully reactive, I also want to provide an example for this setup. In most cases, you just add Spring WebFlux to your existing application to make use of the Spring WebClient. Learn how to configure Spring WebClient for OAuth2 using a Servlet based application in this blog post.

OAuth2 Spring Web project setup

The Maven project for this example is quite similar to the WebFlux application. It includes Thymeleaf, Web, WebFlux, Security and the OAuth2 client:

If you have Spring Web and Spring WebFlux on your classpath, Spring Boot assumes you want to run on Tomcat per default. With this setup, we can use our existing Servlet based applications and just use the WebClient from Spring WebFlux, as the RestTemplate won't receive further updates.

For the rest of the required configuration setup, follow the chapter in the WebFlux blog post.

Securing the Web application with OAuth2 login

The security configuration for a Spring Web application works a little bit different compared to Spring WebFlux. Here we have to extend the WebSecurityConfigurerAdapter class and adjust the configuration by overriding methods.

I'm using the same approach as in the WebFlux example and require authentication for each request. In addition, the OAuth2 login and client support are enabled:

WebClient OAuth2 configuration for a Servlet application

Whereas we created a ServerOAuth2AuthorizedClientExchangeFilterFunction for the WebFlux example, the Servlet approach works with a ServletOAuth2AuthorizedClientExchangeFilterFunction.

The WebClient setup therefor looks quite similar, except that the non-reactive classes are used:

With this setup, we can now inject an OAuth2 pre-configured WebClient instance to our classes.

Accessing OAuth2 protected resources on GitHub

The Thymeleaf page doesn't any adjustments compared to the WebFlux example (you can find it here). That's why I did not include it in this post and just did a small change for the MVC controller.

Whereas we made use of the reactive types Flux and Mono in the WebFlux application, I'm now using .block() on the WebClient request to return a String:

You can find the source code with further instructions on how to run this application on GitHub.

Have fun using the OAuth2 with the Spring WebClient for a Spring Web (Servlet) application,

Phil

>