There is now built in support for OAuth2 and WebClient support. The support allows:
-
Adding the access token to the request
-
Automatic refreshing of the access token when it expires
-
Resolving the access token to use
For example, in a Servlet environment you can configure a Bean like this:
@Bean
WebClient webClient(OAuth2AuthorizedClientRepository repository) {
ServletOAuth2AuthorizedClientExchangeFilterFunction filter =
new ServletOAuth2AuthorizedClientExchangeFilterFunction(repository);
return WebClient.builder()
.filter(new OAuth2AuthorizedClientExchangeFilterFunction())
.apply(filter.oauth2Configuration())
.build();
}
Now you can add the OAuth token in a number of different ways. If you want you can resolve the OAuth2AuthorizedClient
using the Spring MVC support. If the authorization server returned a refresh token and the access token is about to expire, Spring Security will transparently update the access token and submit the updated access token instead.
@GetMapping("/users")
Mono<String> users(@RegisteredOAuth2AuthorizedClient("client-id")
OAuth2AuthorizedClient authorizedClient) {
return this.webClient.get()
.uri("https://api.example.com/user")
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String.class);
}
You can also resolve the access token through the WebClient
. Fore example:
Mono<String> users() {
return this.webClient.get()
.uri("https://api.example.com/user")
.attributes(clientRegistrationId("client-id"))
.retrieve()
.bodyToMono(String.class);
}
If you authenticated using OAuth2 Log In or OIDC, then a default access token can be applied with no user interaction.
Mono<String> users() {
// if Authenticated with OIDC
// OAuth2 Log In use the access token associated to log in
return this.webClient.get()
.uri("https://api.example.com/user")
.retrieve()
.bodyToMono(String.class);
}