Skip to content

Commit

Permalink
Add Bearer authentication intercept (#544)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ferrazoli authored Jan 12, 2025
1 parent 34257d6 commit d7e0b40
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package io.avaje.http.client;

/**
* Adds a Bearer authentication Authorization header to requests.
*/
public final class BearerTokenIntercept implements RequestIntercept {

private final String headerValue;

public BearerTokenIntercept(String token) {
this.headerValue = "Bearer " + token;
}

@Override
public void beforeRequest(HttpClientRequest request) {
request.header("Authorization", headerValue);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package io.avaje.http.client;

import org.junit.jupiter.api.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

class BearerTokenInterceptTest {

@Test
void beforeRequest() {
// setup
final var intercept = new BearerTokenIntercept("api_key");
final var ctx = HttpClient.builder().baseUrl("junk").build();

// act
final HttpClientRequest request = ctx.request();
intercept.beforeRequest(request);

final List<String> values = request.header("Authorization");
assertThat(values).containsExactly("Bearer api_key");
}

}

0 comments on commit d7e0b40

Please sign in to comment.