-
Notifications
You must be signed in to change notification settings - Fork 41
/
BasicAuthenticator.java
52 lines (42 loc) · 1.71 KB
/
BasicAuthenticator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.burgstaller.okhttp.basic;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import java.io.IOException;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.internal.platform.Platform;
import static java.net.HttpURLConnection.HTTP_PROXY_AUTH;
/**
* Standard HTTP basic authenticator.
*/
public class BasicAuthenticator implements CachingAuthenticator {
private final Credentials credentials;
private boolean proxy;
public BasicAuthenticator(Credentials credentials) {
this.credentials = credentials;
}
@Override
public Request authenticate(Route route, Response response) throws IOException {
final Request request = response.request();
proxy = response.code() == HTTP_PROXY_AUTH;
return authFromRequest(request);
}
private Request authFromRequest(Request request) {
// prevent infinite loops when the password is wrong
String header = proxy ? "Proxy-Authorization" : "Authorization";
final String authorizationHeader = request.header(header);
if (authorizationHeader != null && authorizationHeader.startsWith("Basic")) {
Platform.get().log("Previous basic authentication failed, returning null", Platform.WARN, null);
return null;
}
String authValue = okhttp3.Credentials.basic(credentials.getUserName(), credentials.getPassword());
return request.newBuilder()
.header(header, authValue)
.build();
}
@Override
public Request authenticateWithState(Route route, Request request) throws IOException {
return authFromRequest(request);
}
}