Spring Boot 3 Oauth2 Declarative Http Exchange

Karanbir Singh
2 min readMar 3, 2023

--

Spring Boot 3 is just recently launched and one of the attractions with it is the @HttpExhange based declarative HTTP clients.

There are ample amount of articles online which share the details of using the @HttpExhange and it is actually a good way of reducing the extra piece of code while calling the downstream HTTP services.

Those articles are great enough for the normal HTTP APIs & actually solves the purpose.

But what about HTTP APIs which are Oauth2 protected? i.e. HTTP APIs which act Oauth2 Resource Server(s)!

Just recently explored that bit and It is way straightforward than we could expect.

Codebase

I am piggy backing the source code of the previous blog post here.

Without HttpExchange the structure is as below:-

you can observe, when we call the client, it is a repetitive piece of code that we need to write again and again, if it is good number of multiple endpoints for the client, then we will have to write the similar code multiple times.

client.get()
.uri("/v2/ping")
.exchange()
.flatMap(r -> r.bodyToMono(Object.class));

Now With HttpExchange the structure is as below:-

compared to the previous snippet code now it is very short and precise like below:-

public Mono<Object> getPingJwt() {
return clientV1.getPong(); // short and sweet
// previously it was like below:-

/*

clientV1.get()
.uri("/v2/ping")
.exchange()
.flatMap(r -> r.bodyToMono(Object.class));

*/
}

The crux is:-

1. Previously, We had a WebClient which had a filter bounded to oauth2 token creation during preflight downstream call. We used to call it directly

2. We use that same previousWebClient instance + an interface marked with the @HttpExchange and then construct a bean(instance) of Interface using HttpServiceProxyFactory + WebClientAdapter & afterwards we Autowire the interface’s bean directly wherever required

--

--

Karanbir Singh
Karanbir Singh

Written by Karanbir Singh

API developer + Web Application developer + Devops Engineer = Full Stack Developer

No responses yet