-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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.
- Loading branch information
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
19 changes: 19 additions & 0 deletions
19
http-client/src/main/java/io/avaje/http/client/BearerTokenIntercept.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
|
||
} |
25 changes: 25 additions & 0 deletions
25
http-client/src/test/java/io/avaje/http/client/BearerTokenInterceptTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | ||
} | ||
|
||
} |