Skip to content

Commit 97ae981

Browse files
author
Simon Stewart
committed
Handle Authorization challenges when using okhttp
This follows the recipe from `https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Authenticate.java` and allows us to connect to servers that require authentication.
1 parent 8828d59 commit 97ae981

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

java/client/src/org/openqa/selenium/remote/internal/OkHttpClient.java

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,14 @@
1717

1818
package org.openqa.selenium.remote.internal;
1919

20+
import com.google.common.base.Strings;
21+
2022
import org.openqa.selenium.remote.http.HttpClient;
2123
import org.openqa.selenium.remote.http.HttpRequest;
2224
import org.openqa.selenium.remote.http.HttpResponse;
2325

2426
import okhttp3.ConnectionPool;
27+
import okhttp3.Credentials;
2528
import okhttp3.HttpUrl;
2629
import okhttp3.MediaType;
2730
import okhttp3.Request;
@@ -116,12 +119,31 @@ public static class Factory implements HttpClient.Factory {
116119

117120
@Override
118121
public HttpClient createClient(URL url) {
119-
okhttp3.OkHttpClient client = new okhttp3.OkHttpClient.Builder()
122+
okhttp3.OkHttpClient.Builder client = new okhttp3.OkHttpClient.Builder()
120123
.connectionPool(pool)
121124
.followRedirects(true)
122-
.followSslRedirects(true)
123-
.build();
124-
return new OkHttpClient(client, url);
125+
.followSslRedirects(true);
126+
127+
String info = url.getUserInfo();
128+
if (!Strings.isNullOrEmpty(info)) {
129+
String[] parts = info.split(":", 2);
130+
String user = parts[0];
131+
String pass = parts.length > 1 ? parts[1] : null;
132+
133+
String credentials = Credentials.basic(user, pass);
134+
135+
client.authenticator((route, response) -> {
136+
if (response.request().header("Authorization") != null) {
137+
return null; // Give up, we've already attempted to authenticate.
138+
}
139+
140+
return response.request().newBuilder()
141+
.header("Authorization", credentials)
142+
.build();
143+
});
144+
}
145+
146+
return new OkHttpClient(client.build(), url);
125147
}
126148

127149
@Override

0 commit comments

Comments
 (0)