Skip to content

Commit 30d33ca

Browse files
authored
[http-client] Add BasicAuthIntercept.header() helper method (#534)
Provided as a helper method for code that wants the header value to then apply it explicitly [typically as a http Authorization header] rather than using this as a request intercept.
1 parent 97fe4b6 commit 30d33ca

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

http-client/src/main/java/io/avaje/http/client/BasicAuthIntercept.java

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,38 @@
44

55
import java.util.Base64;
66

7-
/** Adds Basic Authorization header to requests. */
7+
/**
8+
* Adds Basic Authorization header to requests.
9+
*/
810
public final class BasicAuthIntercept implements RequestIntercept {
911

1012
private final String headerValue;
1113

12-
/** Construct with the username and password. */
14+
/**
15+
* Construct with the username and password.
16+
*/
1317
public BasicAuthIntercept(String username, String password) {
14-
this.headerValue = "Basic " + encode(username, password);
18+
this.headerValue = header(username, password);
1519
}
1620

17-
/** Return Base64 encoding of {@literal username:password} */
21+
/**
22+
* Return the Basic header value with the encoding of {@literal username:password}
23+
* <p>
24+
* Provided as a helper method for code that wants the header value to then
25+
* apply explicitly rather than using this as a request intercept.
26+
*
27+
* @return {@code "Basic " + encode(username, password)}
28+
*/
29+
public static String header(String username, String password) {
30+
return "Basic " + encode(username, password);
31+
}
32+
33+
/**
34+
* Return Base64 encoding of {@literal username:password}
35+
* <p>
36+
* Provided as a helper method for code that wants to encode the username
37+
* password pair and use that explicitly rather than using this as a request intercept.
38+
*/
1839
public static String encode(String username, String password) {
1940
return Base64.getEncoder().encodeToString((username + ":" + password).getBytes(UTF_8));
2041
}

http-client/src/test/java/io/avaje/http/client/BasicAuthInterceptTest.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,12 @@ void encode() {
1414
assertThat(encode).isEqualTo("QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
1515
}
1616

17+
@Test
18+
void header() {
19+
final String encode = BasicAuthIntercept.header("Aladdin", "open sesame");
20+
assertThat(encode).isEqualTo("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
21+
}
22+
1723
@Test
1824
void beforeRequest() {
1925
// setup

0 commit comments

Comments
 (0)