Dropbox Java: Use Proxy with authentication - java

I want to create my DbxRequestConfig Object with a StandardHttpRequestor, because I need it to use a Proxy.
The Proxy is a http Proxy, Port 80, and needs authentication.
Proxyaddress: http://myproxy.com
Proxyport: 80
Proxyusername: username
Proxypassword: password
So I tried to use the global Java Proxy setup:
System.setProperty("http.proxy","proxyaddress") //... http.proxyUser, http.ProxyPassword
//and so on
It did not work.
After looking into the StandardHttpRequestor I realized I need to use this Object as well as a Proyx Object:
Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(ip,port));
StandardHttpRequestor requ = new StandardHttpRequestor(proxy);
Which is wrong, because it has no authentication.
For authentication, the net and google show me the following. Putting all together, my current code looks like the following:
String ip = "http://myproxy.com";
int port = 80;
final String authUser = "username";
final String authPassword = "password";
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authUser, authPassword.toCharArray());
}
});
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);
Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(ip,port));
StandardHttpRequestor requ = new StandardHttpRequestor(proxy);
return requ;
But this does not work as well.
What am I doing wrong?
I can't seem to get the Proxy to work.

One problem was the http:// in String ip = "http://myproxy.com";
My current code looks the following, and works sometimes. Sometimes not. I have no idea why. Sometimes I have to reallow the App to be connected to my DropBox Account, because the authKey doesn't come through the proxy...
Well at least I got an example working for you guys having the same trouble. Maybe the rest of the problem is on the proxy side? I'll have a further look into this. But here comes my code:
public HttpRequestor getProxy(){
if("true".equals(config.getProperty("proxy","false"))){
String ip = "proxy.myproxy.com";
int port = 80;
final String authUser = "username";
final String authPassword = "password";
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authUser, authPassword.toCharArray());
}
});
Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(ip,port));
HttpRequestor req = new StandardHttpRequestor(proxy);
return req;
}
return null;
}
As you can see I don't use the StandardHttpRequestor anymore. For the Dropbox code it is the following:
HttpRequestor requ = con.getProxy();
if(requ!=null)
config = new DbxRequestConfig(APP_NAME, Locale.getDefault().toString(),requ);
else
config = new DbxRequestConfig(APP_NAME, Locale.getDefault().toString());
As I already said, sometimes it works. Sometimes not. I'm going to write more info about that as soon as I know if it's because of the code or because of the proxy itself.

Related

Proxy authenticator auntenticates HTTP But not HTTPS . Why?

I am using openjdk . For porxy authentication ,I am using Authenticator but for my first Request as HTTPS the authenticators doesn't authenticates and throws error. After connecting through HTTP , HTTPS working fine.
I have tried with setting system property, jdk.http.auth.tunneling.disabledSchemes="" and jdk.http.auth.proxying.disabledSchemes="".
private static void setProxy(String proxyHostName,int proxyport){
proxy=new Proxy(Proxy.Type.HTTP,new InetSocketAddress(proxyHostName,proxyport));
}
private static void setProxy(String proxyHostName,int proxyport,String username,String password){
setProxy(proxyHostName,proxyport);
if (username!=null && password!=null) {
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
System.setProperty("jdk.http.auth.proxying.disabledSchemes", "");
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(username, password.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
}
}
After setting this property in my java_opts in .sh file . It worked fine for me.
Orelse Anyone want to set in their java code means set it in start method.

Proxy problems in okhttp

I am using the OkHttp library to make requests from my application to facebook api, however I need to work on a proxy network, instantiating OkHttpClient() and calling OkHttpClient.newCall(request).execute() I get a timeout message because my proxy stop the request.
After a little research I found the following solution:
int proxyPort = 8080;
String proxyHost = "proxyHost";
final String username = "username";
final String password = "password";
Authenticator proxyAuthenticator = new Authenticator() {
#Override public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(username, password);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
.proxyAuthenticator(proxyAuthenticator)
.build();
This works great, however I would not want to leave the proxy information in the code or in the application.
Is there any way to configure the proxy as environment variable or in some external file where OkHttp would be able to complete the requests?
I would use system environment variables for storing this sensitive configuration. If you do not have property file, system variable would be good option.
You can update you authenticate method to this:
Authenticator proxyAuthenticator = new Authenticator() {
#Override public Request authenticate(Route route, Response response) throws
IOException {
String username = System.getenv("PROXY_USERNAME");
String password = System.getenv("PROXY_PASSWORD");
if (username == null || username.isEmpty() || password == null || password.isEmpty() )
throw new IllegalStateException("Proxy information is not defined in system variables");
String credential = Credentials.basic(username, password);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
and remove
final String username = "username";
final String password = "password";
class fields.
Now when you run your application you can define the variables on the computer itself or better to pass them as parameters to you java application. For instance:
java -jar -DPROXY_USERNAME=userName -DPROXY_PASSWORD=password yourJar.jar

How can I use Socks5 proxy in Okhttp to start http request

How can I use Socks5 proxy in Okhttp to start http request ?
My code:
Proxy proxy = new Proxy(Proxy.Type.SOCKS, InetSocketAddress.createUnresolved(
"socks5host", 80));
OkHttpClient client = new OkHttpClient.Builder()
.proxy(proxy).authenticator(new Authenticator() {
#Override
public Request authenticate(Route route, Response response) throws IOException {
if (HttpUtils.responseCount(response) >= 3) {
return null;
}
String credential = Credentials.basic("user", "psw");
if (credential.equals(response.request().header("Authorization"))) {
return null; // If we already failed with these credentials, don't retry.
}
return response.request().newBuilder().header("Authorization", credential).build();
}
}).build();
Request request = new Request.Builder().url("http://google.com").get().build();
Response response = client.newCall(request).execute(); <--- **Here, always throw java.net.UnknownHostException: Host is unresolved: google.com**
System.out.println(response.body().string());
How to avoid UnknownHostException?
Any example ?
Thanks!
I found a solution: When create a OkHttpClient.Builder(), set a new socketFactory instead of set proxy, and return a sock5 proxy inside socketFactory createSocket.
I think it's the easiest working soulution. But it seems to me that it can be not 100% safe. I took this code from this code from here and modified it because my proxy's RequestorType is SERVER.
Actually, java has a strange api for proxies, you should to set auth for proxy through system env ( you can see it from the same link)
final int proxyPort = 1080; //your proxy port
final String proxyHost = "your proxy host";
final String username = "proxy username";
final String password = "proxy password";
InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestingHost().equalsIgnoreCase(proxyHost)) {
if (proxyPort == getRequestingPort()) {
return new PasswordAuthentication(username, password.toCharArray());
}
}
return null;
}
});
OkHttpClient client = new OkHttpClient.Builder()
.proxy(proxy)
.build();

Implementing sample code for authenticating to Gmail with OAuth2

I use code from this link to access gmail imap server, because I could not find Android-friendly port of javamail with OAUTH support (javamail 1.5.2 or higher).
However, the problem with this code:
public static IMAPStore connectToImap(String host, int port, String userEmail, String oauthToken, boolean debug) throws Exception {
Properties props = new Properties();
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
Session session = Session.getInstance(props);
session.setDebug(debug);
final URLName unusedUrlName = null;
IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
final String emptyPassword = "";
store.connect(host, port, userEmail, emptyPassword);
return store;
}
is that a new Store object is created every time auth token is changed (expires). And then I have to create a new Folder and read my messages again...
My question is:
Is it possible to change auth token without creating a new Store object? I would like to be able to implement something like
store.connect("imap.gmail.com", username, oauth2_access_token)
(example from javamail 1.5.2) to reconnect, without the need to recreate the Store object.
Thank you very much!
If you need to create a new connection with the same Store you should be able to set the property to a new value and make a new connection, without creating a new Store object. Just call props.put with the new value. The Session keeps a reference to the Properties object rather than making a copy of it.

Authenticator for HttpURLConnection works in Froyo but not IceCreamSandwich

I have this code inside a runnable, on Froyo everything works perfectly. But on ICS it says it does connect but gives me a file not found error and returns -1 as the file size.
There is no problem on ICS with a file that does not need authentication.
Is there a different way to authenticate on ICS ? or am I missing some ICS HttpURLConnection detail ?
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,pass);
}
});
URL url = new URL(URLString);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();//connection says that it is connected
final int filesize = c.getContentLength();//file size is -1 when using ICS
c.disconnect();
Also i'm having trouble authenticating to a https url on Froyo, thats a secondary concern at the moment though..
Thanks for helping if you can ..
I have been away for a while, but this is what I am using now. It does work with ICS, i'm not testing with Froyo at the moment so cant say for sure if it works with both ...
private void setAuthenticationCredentials(final String username, final String password) {
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password
.toCharArray());
I've been authenticating my requests usingHttpURLConnection.setRequestProperty() like this:
String unencoded = username + ":" + password;
String encoded = Base64.encodeToString(unencoded.getBytes(), Base64.DEFAULT);
Log.d(getClass().getName(), "encoded: " + encoded);
// Attach as authentication header.
connection.setRequestProperty("Authorization", "Basic " + encoded);
However, this seems to have the opposite problem. It works on 3.0 and higher but not on 2.3.4 and below (the server apparently sends a 400, although the request isn't in the server logs). Please tell me if you get this working/have already got it working, as I will be grateful for the information.

Categories