Skip to content

Commit d7e0b40

Browse files
authored
Add Bearer authentication intercept (#544)
Currently, the documentation provides instructions on how to build a bearer token provider, which assumes that tokens are short-lived and must be refreshed after some time. However, some REST APIs offer a bearer token authentication mechanism that relies on the API key/secret instead of short-lived tokens. Since this is a somewhat common use case, I feel like it makes sense to have this implementation offered out of the box.
1 parent 34257d6 commit d7e0b40

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package io.avaje.http.client;
2+
3+
/**
4+
* Adds a Bearer authentication Authorization header to requests.
5+
*/
6+
public final class BearerTokenIntercept implements RequestIntercept {
7+
8+
private final String headerValue;
9+
10+
public BearerTokenIntercept(String token) {
11+
this.headerValue = "Bearer " + token;
12+
}
13+
14+
@Override
15+
public void beforeRequest(HttpClientRequest request) {
16+
request.header("Authorization", headerValue);
17+
}
18+
19+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package io.avaje.http.client;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import java.util.List;
6+
7+
import static org.assertj.core.api.Assertions.assertThat;
8+
9+
class BearerTokenInterceptTest {
10+
11+
@Test
12+
void beforeRequest() {
13+
// setup
14+
final var intercept = new BearerTokenIntercept("api_key");
15+
final var ctx = HttpClient.builder().baseUrl("junk").build();
16+
17+
// act
18+
final HttpClientRequest request = ctx.request();
19+
intercept.beforeRequest(request);
20+
21+
final List<String> values = request.header("Authorization");
22+
assertThat(values).containsExactly("Bearer api_key");
23+
}
24+
25+
}

0 commit comments

Comments
 (0)