下面列出了怎么用java.net.Authenticator的API类实例代码及写法,或者点击链接到github查看源代码。
private void remove() {
try {
for (final Field f : Authenticator.class.getDeclaredFields()) {
if (f.getType().equals(Authenticator.class)) {
try {
f.setAccessible(true);
Authenticator o = (Authenticator)f.get(null);
if (o == this) {
//this is at the root of any chain of authenticators
Authenticator.setDefault(wrapped);
} else {
removeFromChain(o);
}
} catch (Exception e) {
//ignore
}
}
}
} catch (Throwable t) {
//ignore
}
}
@Override public Credential authenticate(
Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
for (Challenge challenge : challenges) {
if (!"Basic".equalsIgnoreCase(challenge.getScheme())) {
continue;
}
PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(url.getHost(),
getConnectToInetAddress(proxy, url), url.getPort(), url.getProtocol(),
challenge.getRealm(), challenge.getScheme(), url, Authenticator.RequestorType.SERVER);
if (auth != null) {
return Credential.basic(auth.getUserName(), new String(auth.getPassword()));
}
}
return null;
}
@Override public Credential authenticateProxy(
Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
for (Challenge challenge : challenges) {
if (!"Basic".equalsIgnoreCase(challenge.getScheme())) {
continue;
}
InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(
proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(),
url.getProtocol(), challenge.getRealm(), challenge.getScheme(), url,
Authenticator.RequestorType.PROXY);
if (auth != null) {
return Credential.basic(auth.getUserName(), new String(auth.getPassword()));
}
}
return null;
}
private static PasswordAuthentication
privilegedRequestPasswordAuthentication(
final String host,
final InetAddress addr,
final int port,
final String protocol,
final String prompt,
final String scheme,
final URL url,
final RequestorType authType) {
return java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<PasswordAuthentication>() {
public PasswordAuthentication run() {
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("Requesting Authentication: host =" + host + " url = " + url);
}
PasswordAuthentication pass = Authenticator.requestPasswordAuthentication(
host, addr, port, protocol,
prompt, scheme, url, authType);
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null"));
}
return pass;
}
});
}
@Bean
public DefaultBotOptions defaultBotOptions() {
if (properties.hasAuthData()) {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(properties.getUser(), properties.getPassword().toCharArray());
}
});
}
DefaultBotOptions botOptions = new DefaultBotOptions();
botOptions.setProxyHost(properties.getHost());
botOptions.setProxyPort(properties.getPort());
botOptions.setProxyType(properties.getType());
return botOptions;
}
public Authenticator getAuthenticator() {
if (this.authenticator == null && StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password)) {
this.authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (this.getRequestorType().equals(RequestorType.PROXY))
return new PasswordAuthentication(user, password.toCharArray());
else
return null;
}
};
}
return authenticator;
}
private static PasswordAuthentication
privilegedRequestPasswordAuthentication(
final String host,
final InetAddress addr,
final int port,
final String protocol,
final String prompt,
final String scheme,
final URL url,
final RequestorType authType) {
return java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<PasswordAuthentication>() {
public PasswordAuthentication run() {
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("Requesting Authentication: host =" + host + " url = " + url);
}
PasswordAuthentication pass = Authenticator.requestPasswordAuthentication(
host, addr, port, protocol,
prompt, scheme, url, authType);
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null"));
}
return pass;
}
});
}
private void getAnswer() {
if (!answered) {
answered = true;
PasswordAuthentication passAuth =
Authenticator.requestPasswordAuthentication(
hci.host, hci.addr, hci.port, hci.protocol,
hci.prompt, hci.scheme, hci.url, hci.authType);
/**
* To be compatible with existing callback handler implementations,
* when the underlying Authenticator is canceled, username and
* password are assigned null. No exception is thrown.
*/
if (passAuth != null) {
username = passAuth.getUserName();
password = passAuth.getPassword();
}
}
}
@Override public Credential authenticate(
Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
for (Challenge challenge : challenges) {
if (!"Basic".equalsIgnoreCase(challenge.getScheme())) {
continue;
}
PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(url.getHost(),
getConnectToInetAddress(proxy, url), url.getPort(), url.getProtocol(),
challenge.getRealm(), challenge.getScheme(), url, Authenticator.RequestorType.SERVER);
if (auth != null) {
return Credential.basic(auth.getUserName(), new String(auth.getPassword()));
}
}
return null;
}
@Override public Credential authenticateProxy(
Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
for (Challenge challenge : challenges) {
if (!"Basic".equalsIgnoreCase(challenge.getScheme())) {
continue;
}
InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(
proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(),
url.getProtocol(), challenge.getRealm(), challenge.getScheme(), url,
Authenticator.RequestorType.PROXY);
if (auth != null) {
return Credential.basic(auth.getUserName(), new String(auth.getPassword()));
}
}
return null;
}
@Test
public void shouldInitHttpsProxyAuthenticator() throws Exception {
// when
ProxyAuthenticator.initAuthenticator(HTTPS_URL);
PasswordAuthentication testAuthentication =
Authenticator.requestPasswordAuthentication(null, 0, null, null, null);
// then
assertEquals(testAuthentication.getUserName(), "user2");
assertEquals(String.valueOf(testAuthentication.getPassword()), "paswd2");
// when
ProxyAuthenticator.resetAuthenticator();
// then
testAuthentication = Authenticator.requestPasswordAuthentication(null, 0, null, null, null);
assertEquals(testAuthentication, null);
}
/**
* Sets Basic HTTP Authentication the request
*
* @param username The username
* @param password The password
*
* @return TestResponse instance
*/
public TestResponse withBasicAuthentication(String username, String password) {
Objects.requireNonNull(username, Required.USERNAME.toString());
Objects.requireNonNull(password, Required.PASSWORD.toString());
this.authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
username,
password.toCharArray());
}
};
return this;
}
@Override public Credential authenticateProxy(
Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
for (Challenge challenge : challenges) {
if (!"Basic".equalsIgnoreCase(challenge.getScheme())) {
continue;
}
InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(
proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(),
url.getProtocol(), challenge.getRealm(), challenge.getScheme(), url,
Authenticator.RequestorType.PROXY);
if (auth != null) {
return Credential.basic(auth.getUserName(), new String(auth.getPassword()));
}
}
return null;
}
private void getAnswer() {
if (!answered) {
answered = true;
PasswordAuthentication passAuth =
Authenticator.requestPasswordAuthentication(
hci.host, hci.addr, hci.port, hci.protocol,
hci.prompt, hci.scheme, hci.url, hci.authType);
/**
* To be compatible with existing callback handler implementations,
* when the underlying Authenticator is canceled, username and
* password are assigned null. No exception is thrown.
*/
if (passAuth != null) {
username = passAuth.getUserName();
password = passAuth.getPassword();
}
}
}
public Http2Client(String authCode, HttpProxy proxy, ClientConfig config) {
_maxRetryTimes = config.getMaxRetryTimes();
_connectionTimeout = config.getConnectionTimeout();
_readTimeout = config.getReadTimeout();
_sslVer = config.getSSLVersion();
_authCode = authCode;
_proxy = proxy;
_encryptType = config.getEncryptType();
String message = MessageFormat.format("Created instance with "
+ "connectionTimeout {0}, readTimeout {1}, maxRetryTimes {2}, SSL Version {3}",
_connectionTimeout, _readTimeout, _maxRetryTimes, _sslVer);
LOG.info(message);
if (null != _proxy && _proxy.isAuthenticationNeeded()) {
Authenticator.setDefault(new NativeHttpClient.SimpleProxyAuthenticator(
_proxy.getUsername(), _proxy.getPassword()));
}
}
@Test
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/basic-auth"))
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("postman", "password".toCharArray());
}
})
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
/**
* Set a HTTP Proxy.
* WARNING: Authenticated HTTP Proxy won't work from jdk1.8.111 unless
* passing the flag -Djdk.http.auth.tunneling.disabledSchemes="" to java
* see https://stackoverflow.com/q/41505219
*
* @param fullproxy the proxy, using format [user:password]@host[:port]
*/
public static void setHTTPProxy(String fullproxy) {
Map<String, String> proxyServer = parseServer(fullproxy);
if (proxyServer.get("user") != null && proxyServer.get("password") != null) {
Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
PasswordAuthentication p = new PasswordAuthentication(proxyServer.get("user"), proxyServer.get("password").toCharArray());
return p;
}
});
System.setProperty("http.proxyUser", proxyServer.get("user"));
System.setProperty("http.proxyPassword", proxyServer.get("password"));
System.setProperty("https.proxyUser", proxyServer.get("user"));
System.setProperty("https.proxyPassword", proxyServer.get("password"));
}
if (proxyServer.get("port") != null) {
System.setProperty("http.proxyPort", proxyServer.get("port"));
System.setProperty("https.proxyPort", proxyServer.get("port"));
}
System.setProperty("http.proxyHost", proxyServer.get("server"));
System.setProperty("https.proxyHost", proxyServer.get("server"));
}
/**
* Set a Socks Proxy Server (globally).
*
* @param fullsocks the socks server, using format [user:password]@host[:port]
*/
public static void setSocks(String fullsocks) {
Map<String, String> socksServer = parseServer(fullsocks);
if (socksServer.get("user") != null && socksServer.get("password") != null) {
Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
PasswordAuthentication p = new PasswordAuthentication(socksServer.get("user"), socksServer.get("password").toCharArray());
return p;
}
});
System.setProperty("java.net.socks.username", socksServer.get("user"));
System.setProperty("java.net.socks.password", socksServer.get("password"));
}
if (socksServer.get("port") != null) {
System.setProperty("socksProxyPort", socksServer.get("port"));
}
System.setProperty("socksProxyHost", socksServer.get("server"));
}
private static PasswordAuthentication
privilegedRequestPasswordAuthentication(
final String host,
final InetAddress addr,
final int port,
final String protocol,
final String prompt,
final String scheme,
final URL url,
final RequestorType authType) {
return java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<PasswordAuthentication>() {
public PasswordAuthentication run() {
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("Requesting Authentication: host =" + host + " url = " + url);
}
PasswordAuthentication pass = Authenticator.requestPasswordAuthentication(
host, addr, port, protocol,
prompt, scheme, url, authType);
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null"));
}
return pass;
}
});
}
public Webi setProxy(String host, int port, final String username, final String password) {
webService.is_proxy_seted = true;
webService.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", String.valueOf(port));
System.setProperty("http.proxyUser", username);
System.setProperty("http.proxyPassword", password);
Authenticator.setDefault(
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
}
);
return this;
}
public WebiConfig setDefaultProxy(String host, int port, final String username, final String password) {
WebiConfig.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", String.valueOf(port));
System.setProperty("http.proxyUser", username);
System.setProperty("http.proxyPassword", password);
Authenticator.setDefault(
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
}
);
return this;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
Authenticator cxfauth = auth.get();
if (cxfauth == null) {
remove();
}
PasswordAuthentication pauth = null;
if (wrapped != null) {
try {
pauth = tryWith(wrapped);
if (pauth != null) {
return pauth;
}
} catch (Exception e) {
pauth = null;
}
}
if (cxfauth != null) {
try {
pauth = tryWith(cxfauth);
} catch (Exception e1) {
pauth = null;
}
}
return pauth;
}
@Override public Credential authenticateProxy(
Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
for (Challenge challenge : challenges) {
if (!"Basic".equalsIgnoreCase(challenge.getScheme())) {
continue;
}
InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(
proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(),
url.getProtocol(), challenge.getRealm(), challenge.getScheme(), url,
Authenticator.RequestorType.PROXY);
if (auth != null) {
return Credential.basic(auth.getUserName(), new String(auth.getPassword()));
}
}
return null;
}
private void getAnswer() {
if (!answered) {
answered = true;
PasswordAuthentication passAuth =
Authenticator.requestPasswordAuthentication(
hci.host, hci.addr, hci.port, hci.protocol,
hci.prompt, hci.scheme, hci.url, hci.authType);
/**
* To be compatible with existing callback handler implementations,
* when the underlying Authenticator is canceled, username and
* password are assigned null. No exception is thrown.
*/
if (passAuth != null) {
username = passAuth.getUserName();
password = passAuth.getPassword();
}
}
}
/**
* Constructor an un-schemed object for site access.
*/
public HttpCallerInfo(URL url, Authenticator a) {
this.url= url;
prompt = "";
host = url.getHost();
int p = url.getPort();
if (p == -1) {
port = url.getDefaultPort();
} else {
port = p;
}
InetAddress ia;
try {
ia = InetAddress.getByName(url.getHost());
} catch (Exception e) {
ia = null;
}
addr = ia;
protocol = url.getProtocol();
authType = RequestorType.SERVER;
scheme = "";
authenticator = a;
}
private static void setProxySettingForClient() {
System.setProperty("http.proxySet", "true");
System.setProperty("http.proxyHost", "127.0.0.1");
System.setProperty("http.proxyPort", "" + proxyPort);
System.setProperty("http.proxyUser", proxyUsername);
System.setProperty("http.proxyPassword", proxyPassword);
Authenticator.setDefault(new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray());
}
});
}
/**
* Constructor an un-schemed object for site access.
*/
public HttpCallerInfo(URL url, Authenticator a) {
this.url= url;
prompt = "";
host = url.getHost();
int p = url.getPort();
if (p == -1) {
port = url.getDefaultPort();
} else {
port = p;
}
InetAddress ia;
try {
ia = InetAddress.getByName(url.getHost());
} catch (Exception e) {
ia = null;
}
addr = ia;
protocol = url.getProtocol();
authType = RequestorType.SERVER;
scheme = "";
authenticator = a;
}
@BeforeClass
public void setUp() throws Exception {
shouldRun = ensureInet6AddressFamily() && ensureIPv6OnLoopback();
server = HttpServer.create(new InetSocketAddress(0), 0);
server.createContext("/", ex -> {
ex.sendResponseHeaders(200, response.length());
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(ex.getResponseBody(), "UTF-8"))) {
writer.write(response);
}
ex.close();
});
server.start();
socks = new SocksServer(0, false);
socks.addUser("user", "pass");
socks.start();
Authenticator.setDefault(new Authenticator() {
@Override
protected java.net.PasswordAuthentication getPasswordAuthentication() {
return new java.net.PasswordAuthentication(
"user", "pass".toCharArray());
}
});
}
protected void configureProxyServerSettings() throws MojoExecutionException {
Proxy proxy = mavenSession.getSettings().getActiveProxy();
if (proxy != null) {
getLog().info("Using proxy server configured in maven.");
if (proxy.getHost() == null) {
throw new MojoExecutionException("Proxy in settings.xml has no host");
}
if (proxy.getHost() != null) {
System.setProperty(HTTP_PROXY_HOST, proxy.getHost());
}
if (String.valueOf(proxy.getPort()) != null) {
System.setProperty(HTTP_PROXY_PORT, String.valueOf(proxy.getPort()));
}
if (proxy.getNonProxyHosts() != null) {
System.setProperty(HTTP_NON_PROXY_HOSTS, proxy.getNonProxyHosts());
}
if (!StringUtils.isEmpty(proxy.getUsername())
&& !StringUtils.isEmpty(proxy.getPassword())) {
final String authUser = proxy.getUsername();
final String authPassword = proxy.getPassword();
Authenticator.setDefault(new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authUser, authPassword.toCharArray());
}
});
System.setProperty(HTTP_PROXY_USER, authUser);
System.setProperty(HTTP_PROXY_PASSWORD, authPassword);
}
}
}
@BeforeClass
public void setUp() throws Exception {
shouldRun = ensureInet6AddressFamily() && ensureIPv6OnLoopback();
server = HttpServer.create(new InetSocketAddress(0), 0);
server.createContext("/", ex -> {
ex.sendResponseHeaders(200, response.length());
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(ex.getResponseBody(), "UTF-8"))) {
writer.write(response);
}
ex.close();
});
server.start();
socks = new SocksServer(0, false);
socks.addUser("user", "pass");
socks.start();
Authenticator.setDefault(new Authenticator() {
@Override
protected java.net.PasswordAuthentication getPasswordAuthentication() {
return new java.net.PasswordAuthentication(
"user", "pass".toCharArray());
}
});
}