下面列出了怎么用java.net.PasswordAuthentication的API类实例代码及写法,或者点击链接到github查看源代码。
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 boolean handleKenaiAuthorization(SvnKenaiAccessor support, String url) {
PasswordAuthentication pa = support.getPasswordAuthentication(url, true);
if(pa == null) {
return false;
}
String user = pa.getUserName();
char[] password = pa.getPassword();
adapter.setUsername(user != null ? user : "");
if (connectionType != ConnectionType.javahl) {
adapter.setPassword(password != null ? new String(password) : "");
}
return true;
}
private void getAnswer() {
if (!answered) {
answered = true;
if (LoginConfigImpl.HTTP_USE_GLOBAL_CREDS) {
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();
}
}
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
private void init (PasswordAuthentication pw) {
this.pw = pw;
if (pw != null) {
String s = pw.getUserName();
int i = s.indexOf ('\\');
if (i == -1) {
username = s;
ntdomain = defaultDomain;
} else {
ntdomain = s.substring (0, i).toUpperCase();
username = s.substring (i+1);
}
password = new String (pw.getPassword());
} else {
/* credentials will be acquired from OS */
username = null;
ntdomain = null;
password = null;
}
init0();
}
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 init (PasswordAuthentication pw) {
this.pw = pw;
if (pw != null) {
String s = pw.getUserName();
int i = s.indexOf ('\\');
if (i == -1) {
username = s;
ntdomain = defaultDomain;
} else {
ntdomain = s.substring (0, i).toUpperCase();
username = s.substring (i+1);
}
password = new String (pw.getPassword());
} else {
/* credentials will be acquired from OS */
username = null;
ntdomain = null;
password = null;
}
init0();
}
/**
* 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"));
}
/**
* 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"));
}
private PasswordAuthentication getCredential(String msg, boolean proxy) {
JTextField user = new JTextField(30);
JPasswordField pass = new JPasswordField(30);
String prompt = proxy ? StringResource.get("PROMPT_PROXY")
: String.format(StringResource.get("PROMPT_SERVER"), msg);
Object[] obj = new Object[5];
obj[0] = prompt;
obj[1] = StringResource.get("DESC_USER");
obj[2] = user;
obj[3] = StringResource.get("DESC_PASS");
obj[4] = pass;
if (JOptionPane.showOptionDialog(null, obj, StringResource.get("PROMPT_CRED"), JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION) {
PasswordAuthentication pauth = new PasswordAuthentication(user.getText(), pass.getPassword());
return pauth;
}
return null;
}
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;
}
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 readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject ();
pw = new PasswordAuthentication (s1, s2.toCharArray());
s1 = null; s2= null;
}
/**
* Create a BasicAuthentication
*/
public BasicAuthentication(boolean isProxy, URL url, String realm,
PasswordAuthentication pw,
String authenticatorKey) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.BASIC, url, realm,
Objects.requireNonNull(authenticatorKey));
String plain = pw.getUserName() + ":";
byte[] nameBytes = null;
try {
nameBytes = plain.getBytes("ISO-8859-1");
} catch (java.io.UnsupportedEncodingException uee) {
assert false;
}
// get password bytes
char[] passwd = pw.getPassword();
byte[] passwdBytes = new byte[passwd.length];
for (int i=0; i<passwd.length; i++)
passwdBytes[i] = (byte)passwd[i];
// concatenate user name and password bytes and encode them
byte[] concat = new byte[nameBytes.length + passwdBytes.length];
System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
System.arraycopy(passwdBytes, 0, concat, nameBytes.length,
passwdBytes.length);
this.auth = "Basic " + Base64.getEncoder().encodeToString(concat);
this.pw = pw;
}
/**
* Constructor used for proxy entries
*/
public NTLMAuthentication(boolean isProxy, String host, int port,
PasswordAuthentication pw,
String authenticatorKey) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.NTLM,
host,
port,
"",
Objects.requireNonNull(authenticatorKey));
init (pw);
}
public static PasswordAuthentication
getPasswordAuthentication(
String realm,
URL tracker )
{
return( SESecurityManagerImpl.getSingleton().getPasswordAuthentication(realm, tracker));
}
public DigestAuthentication(boolean isProxy, String host, int port, String realm,
String authMethod, PasswordAuthentication pw,
Parameters params) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.DIGEST,
host,
port,
realm);
this.authMethod = authMethod;
this.pw = pw;
this.params = params;
}
AuthenticationInfo create(boolean isProxy,
String host,
int port,
PasswordAuthentication pw) {
try {
return fiveArgCtr.newInstance(isProxy, host, port, pw);
} catch (ReflectiveOperationException roe) {
finest(roe);
}
return null;
}
AuthenticationInfo create(boolean isProxy,
URL url,
PasswordAuthentication pw) {
try {
return threeArgCtr.newInstance(isProxy, url, pw);
} catch (ReflectiveOperationException roe) {
finest(roe);
}
return null;
}
/**
* Create a BasicAuthentication
*/
public BasicAuthentication(boolean isProxy, String host, int port,
String realm, PasswordAuthentication pw) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.BASIC, host, port, realm);
String plain = pw.getUserName() + ":";
byte[] nameBytes = null;
try {
nameBytes = plain.getBytes("ISO-8859-1");
} catch (java.io.UnsupportedEncodingException uee) {
assert false;
}
// get password bytes
char[] passwd = pw.getPassword();
byte[] passwdBytes = new byte[passwd.length];
for (int i=0; i<passwd.length; i++)
passwdBytes[i] = (byte)passwd[i];
// concatenate user name and password bytes and encode them
byte[] concat = new byte[nameBytes.length + passwdBytes.length];
System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
System.arraycopy(passwdBytes, 0, concat, nameBytes.length,
passwdBytes.length);
this.auth = "Basic " + Base64.getEncoder().encodeToString(concat);
this.pw = pw;
}
/**
* Create a BasicAuthentication
*/
public BasicAuthentication(boolean isProxy, URL url, String realm,
PasswordAuthentication pw) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.BASIC, url, realm);
String plain = pw.getUserName() + ":";
byte[] nameBytes = null;
try {
nameBytes = plain.getBytes("ISO-8859-1");
} catch (java.io.UnsupportedEncodingException uee) {
assert false;
}
// get password bytes
char[] passwd = pw.getPassword();
byte[] passwdBytes = new byte[passwd.length];
for (int i=0; i<passwd.length; i++)
passwdBytes[i] = (byte)passwd[i];
// concatenate user name and password bytes and encode them
byte[] concat = new byte[nameBytes.length + passwdBytes.length];
System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
System.arraycopy(passwdBytes, 0, concat, nameBytes.length,
passwdBytes.length);
this.auth = "Basic " + Base64.getEncoder().encodeToString(concat);
this.pw = pw;
}
/**
* Create a NTLMAuthentication:
* Username may be specified as domain<BACKSLASH>username in the application Authenticator.
* If this notation is not used, then the domain will be taken
* from a system property: "http.auth.ntlm.domain".
*/
public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.NTLM,
url,
"");
init (pw);
}
/**
* Create a NTLMAuthentication:
* Username may be specified as domain<BACKSLASH>username in the application Authenticator.
* If this notation is not used, then the domain will be taken
* from a system property: "http.auth.ntlm.domain".
*/
public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.NTLM,
url,
"");
init (pw);
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
System.out.println("getPasswordAuthentication() called, scheme: "
+ getRequestingScheme());
if (getRequestingScheme().equalsIgnoreCase("ntlm")) {
return new PasswordAuthentication("test", "test".toCharArray());
}
return null;
}
/**
* Constructor used for proxy entries
*/
public NTLMAuthentication(boolean isProxy, String host, int port,
PasswordAuthentication pw,
String authenticatorKey) {
super(isProxy?PROXY_AUTHENTICATION:SERVER_AUTHENTICATION,
AuthScheme.NTLM,
host,
port,
"",
Objects.requireNonNull(authenticatorKey));
init (pw);
}
/**
* Constructor used for proxy entries
*/
public NTLMAuthentication(boolean isProxy, String host, int port,
PasswordAuthentication pw) {
super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
AuthScheme.NTLM,
host,
port,
"");
init (pw);
}
static BadAuthProxyServer startServer() throws IOException {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xyz", "xyz".toCharArray());
}
});
BadAuthProxyServer server = new BadAuthProxyServer(new ServerSocket(0));
Thread serverThread = new Thread(server);
serverThread.start();
return server;
}
public void testIsAuthenticationDialogNotSuppressed() throws Exception {
final boolean[] suppressed = new boolean[1];
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
suppressed[0] = NetworkSettings.isAuthenticationDialogSuppressed();
return super.getPasswordAuthentication();
}
});
Authenticator.requestPasswordAuthentication("wher.ev.er", Inet4Address.getByName("1.2.3.4"), 1234, "http", null, "http");
assertFalse(suppressed[0]);
}
static BadAuthProxyServer startServer() throws IOException {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xyz", "xyz".toCharArray());
}
});
BadAuthProxyServer server = new BadAuthProxyServer(new ServerSocket(0));
Thread serverThread = new Thread(server);
serverThread.start();
return server;
}