Home » Eclipse Projects » EGit / JGit » Git connectivity via Proxy using JGit API(Proxy Authentication during Git workflows using JGit API)
Git connectivity via Proxy using JGit API [message #1855955] |
Fri, 11 November 2022 06:02  |
Eclipse User |
|
|
|
Hi Team,
We have a requirement to connect to Git Server via Proxy using JGit API. So in this approach, to connect to Git Server sitting behind proxy, with JGit API, before executing JGit API Commands, we have to set the Proxy Authenticator and also the ProxySelector at the JVM level which might be resulting into overriding the Authenticator in case of different threads setting and accessing the Authenticator, when there are multiple proxies being used within the application.
java.net.Authenticator.setDefault(getProxyAuthenticator(proxyUserName, proxyPassword));
Is there any other way of implementation or approach where we can avoid this use case?
In case of Git REST API, we don't see any issues, as we set the Proxy Authentication Header at the HttpRequest Builder object which would be set at every request.
HttpRequest.newBuilder().header(PROXY_AUTHORIZATION, "ABCD=");
Any help would be highly appreciated, thanks in advance.
|
|
| |
Re: Git connectivity via Proxy using JGit API [message #1855976 is a reply to message #1855973] |
Sun, 13 November 2022 23:31   |
Eclipse User |
|
|
|
Hi Thomas, thanks for your quick reply.
I am not using Git with SSH connections, its with HTTP only [Command base and REST API workflows]. In REST API workflows it works fine as we are using the "Proxy-Authorization" header with the Proxy authentication value. But when we are connecting to the Git via Git HttpTransport commands, then it needs the Authenticator to be set at the JVM level.
I have done similar to the SSH connections, but it does still need the Authenticator to be set at the JVM level.
I have put the Test Git Client Program below:
If I comment out the line "Authenticator.setDefault(getAuthenticator(proxyUserName, proxyPassword));", then I would get the below error. Setting TransportConfigCallback is not needed as the Proxy Authentication works independent of this, as it depends on JVM default Authenticator which has to be set manually.
Caused by: org.eclipse.jgit.errors.TransportException: https://token@github.com/<UserName>/<UserRepo>.git: 407 Proxy Auth Required
at org.eclipse.jgit.transport.TransportHttp.connect(TransportHttp.java:719)
at org.eclipse.jgit.transport.TransportHttp.openFetch(TransportHttp.java:465)
at org.eclipse.jgit.api.LsRemoteCommand.execute(LsRemoteCommand.java:167)
---------------------------------------------------------------------------------------------------------------------------------------------
import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jgit.api.LsRemoteCommand;
import org.eclipse.jgit.api.TransportConfigCallback;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.HttpTransport;
import org.eclipse.jgit.transport.Transport;
import org.eclipse.jgit.transport.TransportHttp;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.transport.http.JDKHttpConnectionFactory;
public class TestGitProxyClient {
public static void main(String[] args) {
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
String gitRepoURL = "https://github.com/<UserName>/<UserRepo>.git";
String userName = "<UserName>";
String password = "<Password>";
String accessToken = "<UserToken>";
String proxyHost = "localhost";
String proxyUserName = "admin";
String proxyPassword = "admin";
int proxyPort = 8888;
userName = "PRIVATE-TOKEN";
gitRepoURL = constructGitURL(gitRepoURL, accessToken);
Authenticator.setDefault(getAuthenticator(proxyUserName, proxyPassword));
ProxySelector.setDefault(getProxy(proxyHost, proxyPort));
CredentialsProvider credentialsProvider = getCredentialsProvider(userName, password);
boolean isValidConn = authenticate(gitRepoURL, credentialsProvider, proxyHost, proxyPort);
if (isValidConn) {
System.out.println("Authentication Successful !!!");
} else {
System.out.println("Authentication Failure !!!");
}
}
public static CredentialsProvider getCredentialsProvider(String repoUsername, String repoPassword) {
CredentialsProvider credentialsProvider = null;
if (repoUsername != null && repoUsername.trim().length() > 0 && repoPassword != null
&& repoPassword.trim().length() > 0) {
credentialsProvider = new UsernamePasswordCredentialsProvider(repoUsername, repoPassword.toCharArray());
}
return credentialsProvider;
}
public static boolean authenticate(String repoURL, CredentialsProvider credentialsProvider, String proxyHost,
int proxyPort) {
boolean valid = false;
System.out.println("Validating User Authentication");
try {
LsRemoteCommand lsRemoteCmd = new LsRemoteCommand(null).setCredentialsProvider(credentialsProvider)
.setRemote(repoURL);
lsRemoteCmd.setTransportConfigCallback(getProxyTransportConfig(repoURL, proxyHost, proxyPort));
lsRemoteCmd.call();
valid = true;
} catch (InvalidRemoteException | TransportException exception) {
exception.printStackTrace();
} catch (GitAPIException apiException) {
apiException.printStackTrace();
} catch (Exception exception) {
exception.printStackTrace();
}
return valid;
}
public static TransportConfigCallback getProxyTransportConfig(String repoURL, String proxyHost, int proxyPort) {
TransportConfigCallback transportConfigCallback = null;
try {
URL repoURLObj = new URL(repoURL);
JDKHttpConnectionFactory httpConnFactory = new JDKHttpConnectionFactory();
InetSocketAddress sockAddress = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.HTTP, sockAddress);
httpConnFactory.create(repoURLObj, proxy);
transportConfigCallback = new TransportConfigCallback() {
@Override
public void configure(Transport transport) {
TransportHttp transHttp = (TransportHttp) transport;
Map<String, String> headers = new HashMap<String, String>();
String authHeader = new String(
Base64.getEncoder().encode(new String("admin" + ":" + "admin").getBytes()));
headers.put("Proxy-Authorization", "Basic " + authHeader);
transHttp.setAdditionalHeaders(headers);
HttpTransport.setConnectionFactory(httpConnFactory);
}
};
} catch (Exception exception) {
exception.printStackTrace();
}
return transportConfigCallback;
}
public static Authenticator getAuthenticator(String proxyUserName, String proxyPassword) {
return new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType().equals(RequestorType.PROXY)) {
return new PasswordAuthentication(proxyUserName, proxyPassword.toCharArray());
}
return null;
}
};
}
public static ProxySelector getProxy(String proxyHost, int proxyPort) {
return new ProxySelector() {
final ProxySelector delegate = ProxySelector.getDefault();
InetSocketAddress sockAddress = new InetSocketAddress(proxyHost, proxyPort);
@Override
public List<Proxy> select(URI uri) {
if (uri.toString().toLowerCase().contains("git") && uri.toString().contains("https")) {
return Arrays.asList(new Proxy(Type.HTTP, sockAddress));
}
return delegate == null ? Arrays.asList(Proxy.NO_PROXY) : delegate.select(uri);
}
@Override
public void connectFailed(URI uri, SocketAddress sockAddress, IOException ioException) {
if (uri == null || sockAddress == null || ioException == null) {
throw new IllegalArgumentException("Arguments can't be null.");
}
}
};
}
public static String normalizeURL(final String url) {
// Normalize url by trimming whitespace and never end with '/'
String normalizedUrl = url.trim();
while (normalizedUrl.endsWith("/")) {
normalizedUrl = normalizedUrl.substring(0, normalizedUrl.length() - 1);
}
return normalizedUrl;
}
public static String constructGitURL(final String gitRepoURL, String m_userPersonalAccessToken) {
try {
if (gitRepoURL.startsWith("http")) {
StringBuffer sbURL = new StringBuffer();
URL gitURL = new URL(normalizeURL(gitRepoURL));
sbURL.append(gitURL.getProtocol())
.append("://token:").append(m_userPersonalAccessToken).append("@").append(gitURL.getHost())
.append(gitURL.getPort() == -1 ? "" : ":" + gitURL.getPort()).append(gitURL.getPath());
return sbURL.toString();
}
} catch (Exception exception) {
exception.printStackTrace();
}
return gitRepoURL;
}
}
---------------------------------------------------------------------------------------------------------------------------------------------
|
|
| |
Re: Git connectivity via Proxy using JGit API [message #1863409 is a reply to message #1862684] |
Wed, 31 January 2024 13:52  |
Eclipse User |
|
|
|
Hi Zachary, We have run into the same issue. It seems the the Proxy-Authorization credentials are just not being sent in the initial CONNECT request. For us even Authenticator.setDefault is not working. I have posted my question on stack overflow : question no: 77829326 (not able to post the link here :) )
Did you find any solution for it?
|
|
|
Goto Forum:
Current Time: Sat May 17 09:30:06 EDT 2025
Powered by FUDForum. Page generated in 0.03830 seconds
|