Skip to content
New issue

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

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

Already on GitHub? # to your account

Add support for basic authentication #705

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
12 changes: 12 additions & 0 deletions src/main/java/org/gitlab4j/api/GitLabApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,18 @@ public GitLabApi withRequestResponseLogging(Logger logger, Level level) {
return (this);
}


/**
* Enable basic authentication when connecting to the gitlab server.
*
* @param userName the user name
* @param password the password
*/
public GitLabApi enableBasicAuthentication(String userName, String password) {
apiClient.enableBasicAuthentication(userName, password);
return (this);
}

/**
* Enable the logging of the requests to and the responses from the GitLab server API
* using the GitLab4J shared Logger instance and Level.FINE as the level.
Expand Down
21 changes: 21 additions & 0 deletions src/main/java/org/gitlab4j/api/GitLabApiClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ public class GitLabApiClient implements AutoCloseable {
private Integer sudoAsId;
private Integer connectTimeout;
private Integer readTimeout;
private boolean basicAuthIsEnabled = false;
private String basicAuthUserName;
private String basicAuthPassword;

/**
* Construct an instance to communicate with a GitLab API server using the specified GitLab API version,
Expand Down Expand Up @@ -255,6 +258,18 @@ public void close() {
}
}

/**
* Enable basic authentication
*
* @param userName the user name
* @param password the password
*/
void enableBasicAuthentication(String userName, String password) {
basicAuthIsEnabled = true;
basicAuthUserName = userName;
basicAuthPassword = password;
}

/**
* Enable the logging of the requests to and the responses from the GitLab server API.
*
Expand Down Expand Up @@ -799,6 +814,12 @@ protected Invocation.Builder invocation(URL url, MultivaluedMap<String, String>
} else {
builder = builder.header(authHeader, authValue).accept(accept);
}
/* For servers with basic authentication enabled. */
if (basicAuthIsEnabled) {
String rawString = basicAuthUserName + ":" + basicAuthPassword;
String headerValue = "Basic " + java.util.Base64.getEncoder().encodeToString(rawString.getBytes());
builder.header(AUTHORIZATION_HEADER, headerValue);
}

// If sudo as ID is set add the Sudo header
if (sudoAsId != null && sudoAsId.intValue() > 0)
Expand Down