1 package org.jsoup.helper; 2 3 import org.jsoup.Connection; 4 import org.jspecify.annotations.Nullable; 5 6 import java.net.Authenticator; 7 import java.net.PasswordAuthentication; 8 import java.net.URL; 9 10 /** 11 A {@code RequestAuthenticator} is used in {@link Connection} to authenticate if required to proxies and web 12 servers. See {@link Connection#auth(RequestAuthenticator)}. 13 */ 14 @FunctionalInterface 15 public interface RequestAuthenticator { 16 17 /** 18 Provide authentication credentials for the provided Request Context. 19 * @param auth the request context including URL, type (Server or Proxy), and realm. 20 * @return credentials for the request. May return {@code null} if they are not applicable -- but the request will 21 * likely fail, as this method is only called if the request asked for authentication. 22 */ 23 @Nullable authenticate(Context auth)24 PasswordAuthentication authenticate(Context auth); 25 26 /** 27 Provides details for the request, to determine the appropriate credentials to return. 28 */ 29 class Context { 30 private final URL url; 31 private final Authenticator.RequestorType type; 32 private final String realm; 33 Context(URL url, Authenticator.RequestorType type, String realm)34 Context(URL url, Authenticator.RequestorType type, String realm) { 35 this.url = url; 36 this.type = type; 37 this.realm = realm; 38 } 39 40 /** 41 Get he URL that is being requested. 42 * @return URL 43 */ url()44 public URL url() { 45 return url; 46 } 47 48 /** 49 Get the requestor type: {@link Authenticator.RequestorType#PROXY PROXY} if a proxy is requesting 50 authentication, or {@link Authenticator.RequestorType#SERVER SERVER} if the URL's server is requesting. 51 * @return requestor type 52 */ type()53 public Authenticator.RequestorType type() { 54 return type; 55 } 56 57 /** 58 Get the realm of the authentication request. 59 * @return realm of the authentication request 60 */ realm()61 public String realm() { 62 return realm; 63 } 64 65 /** 66 Gets if the authentication request is for a proxy. 67 * @return true if type==proxy. 68 */ isProxy()69 public boolean isProxy() { 70 return type == Authenticator.RequestorType.PROXY; 71 } 72 73 /** 74 Gets if the authentication request is for a server. 75 * @return true if type==server. 76 */ isServer()77 public boolean isServer() { 78 return type == Authenticator.RequestorType.SERVER; 79 } 80 81 /** 82 Helper method to return a PasswordAuthentication object. 83 * @param username username credential 84 * @param password password credential 85 * @return a constructed PasswordAuthentication 86 */ credentials(String username, String password)87 public PasswordAuthentication credentials(String username, String password) { 88 return new PasswordAuthentication(username, password.toCharArray()); 89 } 90 } 91 92 } 93