Skip to content

Commit

Permalink
[http-client] Add BasicAuthIntercept.header() helper method
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
rbygrave committed Dec 16, 2024
1 parent 5d0852c commit 7075833
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,38 @@

import java.util.Base64;

/** Adds Basic Authorization header to requests. */
/**
* Adds Basic Authorization header to requests.
*/
public final class BasicAuthIntercept implements RequestIntercept {

private final String headerValue;

/** Construct with the username and password. */
/**
* Construct with the username and password.
*/
public BasicAuthIntercept(String username, String password) {
this.headerValue = "Basic " + encode(username, password);
this.headerValue = header(username, password);
}

/** Return Base64 encoding of {@literal username:password} */
/**
* Return the Basic header value with the encoding of {@literal username:password}
* <p>
* Provided as a helper method for code that wants the header value to then
* apply explicitly rather than using this as a request intercept.
*
* @return {@code "Basic " + encode(username, password)}
*/
public static String header(String username, String password) {
return "Basic " + encode(username, password);
}

/**
* Return Base64 encoding of {@literal username:password}
* <p>
* Provided as a helper method for code that wants to encode the username
* password pair and use that explicitly rather than using this as a request intercept.
*/
public static String encode(String username, String password) {
return Base64.getEncoder().encodeToString((username + ":" + password).getBytes(UTF_8));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ void encode() {
assertThat(encode).isEqualTo("QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
}

@Test
void header() {
final String encode = BasicAuthIntercept.header("Aladdin", "open sesame");
assertThat(encode).isEqualTo("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
}

@Test
void beforeRequest() {
// setup
Expand Down

0 comments on commit 7075833

Please sign in to comment.