Closed
Description
With this we can register a AuthTokenProvider that can be used to make a request to obtain a token and register it along with it's valid time. All requests (apart from the request to obtain the token) get this token applied to the request automatically - the token is obtained/refreshed automatically.
Implement AuthTokenProvider
static class MyAuthTokenProvider implements AuthTokenProvider {
@Override
public AuthToken obtainToken(HttpClientRequest tokenRequest) {
AuthTokenResponse res = tokenRequest
.url("https://foo/token")
.body(authRequestBean())
.post()
.bean(AuthTokenResponse.class);
String accessToken = res.getAccessToken();
Instant validUntil = Instant.now().plusSeconds(res.getExpiresIn()).minusSeconds(60);
return AuthToken.of(accessToken, validUntil);
}
}
Register the AuthTokenProvider
Use withAuthTokenProvider()
to register the AuthTokenProvider implementation.
HttpClientContext ctx = HttpClientContext.newBuilder()
.withBaseUrl("https://foo/api")
.withAuthTokenProvider(new MyAuthTokenProvider()) // <----- HERE
.withBodyAdapter(new JacksonBodyAdapter(objectMapper))
.withRequestListener(new RequestLogger())
.build();
Use HttpClientContext as normal
Just use HttpClientContext to make requests as normal. These requests will automatically get the Authorization
header added with the Bearer
token.
Bazz response = ctx.request()
.path(path)
.header("my-header", "to-fa-ti") // the Authorization header with bearer token will be added automatically
.body(requestPayload)
.post()
.bean(Bazz.class);