Skip to content

[http-client] Add BasicAuthIntercept.header() helper method #534

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading