use of java.net.PasswordAuthentication in project Payara by payara.
the class HttpAuthenticator method getPasswordAuthentication.
/**
* This is called when authentication is needed for a protected
* web resource. It looks for the authentication data in the subject.
* If the data is not found then login is invoked on the login context.
*/
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String user = null;
char[] password = null;
Subject subject = null;
String scheme = getRequestingScheme();
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("scheme=" + scheme);
_logger.fine("requesting prompt=" + getRequestingPrompt());
_logger.fine("requesting protocol=" + getRequestingProtocol());
}
ClientSecurityContext cont = ClientSecurityContext.getCurrent();
subject = (cont != null) ? cont.getSubject() : null;
user = getUserName(subject);
password = getPassword(subject);
if (user == null || password == null) {
try {
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("Initiating login again...");
}
securityInfo.doClientLogin(loginType);
cont = ClientSecurityContext.getCurrent();
subject = cont.getSubject();
user = getUserName(subject);
password = getPassword(subject);
} catch (Exception e) {
_logger.log(Level.FINE, "Exception " + e.toString(), e);
return null;
}
}
if (_logger.isLoggable(Level.FINE)) {
_logger.fine("Username:" + user);
}
return new PasswordAuthentication(user, password);
}
use of java.net.PasswordAuthentication in project proxyee-down by monkeyWie.
the class AppUtil method download.
/**
* 下载http资源
*/
public static void download(String url, String path) throws IOException {
URL u = new URL(url);
HttpURLConnection connection;
ProxyConfig proxyConfig = PDownConfigContent.getInstance().get().getProxyConfig();
if (proxyConfig != null) {
Type type;
if (proxyConfig.getProxyType() == ProxyType.HTTP) {
type = Type.HTTP;
} else {
type = Type.SOCKS;
}
if (!StringUtils.isEmpty(proxyConfig.getUser())) {
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(proxyConfig.getUser(), proxyConfig.getPwd() == null ? null : proxyConfig.getPwd().toCharArray());
}
};
Authenticator.setDefault(authenticator);
}
Proxy proxy = new Proxy(type, new InetSocketAddress(proxyConfig.getHost(), proxyConfig.getPort()));
connection = (HttpURLConnection) u.openConnection(proxy);
} else {
connection = (HttpURLConnection) u.openConnection();
}
connection.setConnectTimeout(30000);
connection.setReadTimeout(0);
File file = new File(path);
if (!file.exists() || file.isDirectory()) {
FileUtil.createFileSmart(file.getPath());
}
try (InputStream input = connection.getInputStream();
FileOutputStream output = new FileOutputStream(file)) {
byte[] bts = new byte[8192];
int len;
while ((len = input.read(bts)) != -1) {
output.write(bts, 0, len);
}
}
}
use of java.net.PasswordAuthentication in project jgnash by ccavanaugh.
the class NetworkAuthenticator method getPasswordAuthentication.
@Override
protected PasswordAuthentication getPasswordAuthentication() {
final Preferences auth = Preferences.userRoot().node(NODEHTTP);
final ResourceBundle resources = ResourceUtils.getBundle();
final char[][] pass = { null };
final String[] user = new String[1];
// get the password
if (auth.get(HTTPPASS, null) != null && !auth.get(HTTPPASS, null).isEmpty()) {
pass[0] = auth.get(HTTPPASS, null).toCharArray();
}
// get the user
user[0] = auth.get(HTTPUSER, null);
if (user[0] != null) {
if (user[0].length() <= 0) {
user[0] = null;
}
}
// if either returns null, pop a dialog
if (user[0] == null || pass[0] == null) {
final Dialog<Pair<String, String>> dialog = new Dialog<>();
dialog.setTitle(resources.getString("Title.HTTPProxy"));
dialog.setHeaderText(resources.getString("Message.EnterNetworkAuth"));
// Set the button types.
final ButtonType loginButtonType = new ButtonType(resources.getString("Button.Ok"), ButtonBar.ButtonData.OK_DONE);
ThemeManager.applyStyleSheets(dialog.getDialogPane());
dialog.getDialogPane().getStyleClass().addAll("dialog");
dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
// Create the username and password labels and fields.
final GridPane grid = new GridPane();
grid.getStyleClass().addAll("form");
final TextField userNameField = new TextField();
final PasswordField passwordField = new PasswordField();
grid.add(new Label(resources.getString("Label.UserName")), 0, 0);
grid.add(userNameField, 1, 0);
grid.add(new Label(resources.getString("Label.Password")), 0, 1);
grid.add(passwordField, 1, 1);
// Enable/Disable login button depending on whether a username was entered.
final Node loginButton = dialog.getDialogPane().lookupButton(loginButtonType);
loginButton.setDisable(true);
// bind the button, must not be empty
loginButton.disableProperty().bind(userNameField.textProperty().isEmpty());
dialog.getDialogPane().setContent(grid);
// Request focus on the username field by default.
JavaFXUtils.runLater(userNameField::requestFocus);
dialog.setResultConverter(dialogButton -> {
if (dialogButton == loginButtonType) {
return new Pair<>(userNameField.getText(), passwordField.getText());
}
return null;
});
final Optional<Pair<String, String>> result = dialog.showAndWait();
result.ifPresent(usernamePassword -> {
user[0] = usernamePassword.getKey();
pass[0] = usernamePassword.getValue().toCharArray();
});
}
return new PasswordAuthentication(user[0], pass[0] != null ? pass[0] : new char[0]);
}
use of java.net.PasswordAuthentication in project grpc-java by grpc.
the class ProxyDetectorImplTest method authRequired.
@Test
public void authRequired() throws Exception {
Proxy proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, unresolvedProxy);
final String proxyUser = "testuser";
final String proxyPassword = "testpassword";
PasswordAuthentication auth = new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
when(authenticator.requestPasswordAuthentication(anyString(), ArgumentMatchers.<InetAddress>any(), anyInt(), anyString(), anyString(), AdditionalMatchers.or(anyString(), ArgumentMatchers.<String>any()))).thenReturn(auth);
when(proxySelector.select(any(URI.class))).thenReturn(ImmutableList.of(proxy));
ProxiedSocketAddress detected = proxyDetector.proxyFor(destination);
assertEquals(HttpConnectProxiedSocketAddress.newBuilder().setTargetAddress(destination).setProxyAddress(new InetSocketAddress(InetAddress.getByName(unresolvedProxy.getHostName()), unresolvedProxy.getPort())).setUsername(proxyUser).setPassword(proxyPassword).build(), detected);
}
use of java.net.PasswordAuthentication in project java-cloudant by cloudant.
the class ClientBuilder method build.
/**
* Build the {@link CloudantClient} instance based on the endpoint used to construct this
* client builder and the options that have been set on it before calling this method.
*
* @return the {@link CloudantClient} instance for the specified end point and options
*/
public CloudantClient build() {
logger.config("Building client using URL: " + url);
// Build properties and couchdb client
CouchDbProperties props = new CouchDbProperties(url);
props.addRequestInterceptors(USER_AGENT_INTERCEPTOR);
if (this.iamApiKey != null) {
// Create IAM cookie interceptor and set in HttpConnection interceptors
IamCookieInterceptor cookieInterceptor = new IamCookieInterceptor(this.iamApiKey, this.url.toString(), this.proxyURL);
props.addRequestInterceptors(cookieInterceptor);
props.addResponseInterceptors(cookieInterceptor);
logger.config("Added IAM cookie interceptor");
if (this.iamServerClientId != null && this.iamServerClientSecret != null) {
props.addRequestInterceptors(new IamServerBasicAuthInterceptor(cookieInterceptor.getIamServerUrl(), iamServerClientId, iamServerClientSecret));
}
} else // Create cookie interceptor
if (this.username != null && this.password != null) {
// make interceptor if both username and password are not null
// Create cookie interceptor and set in HttpConnection interceptors
CookieInterceptor cookieInterceptor = new CookieInterceptor(username, password, this.url.toString(), this.proxyURL);
props.addRequestInterceptors(cookieInterceptor);
props.addResponseInterceptors(cookieInterceptor);
logger.config("Added cookie interceptor");
} else {
// If username or password is null, throw an exception
if (username != null || password != null) {
// Username and password both have to contain values
throw new CouchDbException("Either a username and password must be provided, or " + "both values must be null. Please check the credentials and try again.");
}
}
// If setter methods for read and connection timeout are not called, default values
// are used.
logger.config(String.format("Connect timeout: %s %s", connectTimeout, connectTimeoutUnit));
logger.config(String.format("Read timeout: %s %s", readTimeout, readTimeoutUnit));
// Log a warning if the DNS cache time is too long
try {
boolean shouldLogValueWarning = false;
boolean isUsingDefaultTTLValue = true;
String ttlString = Security.getProperty("networkaddress.cache.ttl");
// Was able to access the property
if (ttlString != null) {
try {
int ttl = Integer.parseInt(ttlString);
isUsingDefaultTTLValue = false;
logger.finest("networkaddress.cache.ttl was " + ttl);
if (ttl > 30 || ttl < 0) {
shouldLogValueWarning = true;
}
} catch (NumberFormatException nfe) {
// Suppress the exception, this will result in the default being used
logger.finest("networkaddress.cache.ttl was not an int.");
}
}
if (isUsingDefaultTTLValue && System.getSecurityManager() != null) {
// If we're using a default value and there is a SecurityManager we need to warn
shouldLogValueWarning = true;
}
if (shouldLogValueWarning) {
logger.warning("DNS cache lifetime may be too long. DNS cache lifetimes in excess" + " of 30 seconds may impede client operation during cluster failover.");
}
} catch (SecurityException e) {
// Couldn't access the property; log a warning
logger.warning("Permission denied to check Java DNS cache TTL. If the cache " + "lifetime is too long cluster failover will be impeded.");
}
props.addRequestInterceptors(new TimeoutCustomizationInterceptor(connectTimeout, connectTimeoutUnit, readTimeout, readTimeoutUnit));
// Set connect options
props.setMaxConnections(maxConnections);
props.setProxyURL(proxyURL);
if (proxyUser != null) {
// if there was proxy auth information set up proxy auth
if ("http".equals(url.getProtocol())) {
// If we are using http, create an interceptor to add the Proxy-Authorization header
props.addRequestInterceptors(new ProxyAuthInterceptor(proxyUser, proxyPassword));
logger.config("Added proxy auth interceptor");
} else {
// Set up an authenticator
props.setProxyAuthentication(new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()));
}
}
if (isSSLAuthenticationDisabled) {
props.addRequestInterceptors(SSLCustomizerInterceptor.SSL_AUTH_DISABLED_INTERCEPTOR);
logger.config("SSL authentication is disabled");
}
if (authenticatedModeSSLSocketFactory != null) {
props.addRequestInterceptors(new SSLCustomizerInterceptor(authenticatedModeSSLSocketFactory));
logger.config("Added custom SSL socket factory");
}
// Set http connection interceptors
if (requestInterceptors != null) {
for (HttpConnectionRequestInterceptor requestInterceptor : requestInterceptors) {
props.addRequestInterceptors(requestInterceptor);
logger.config("Added request interceptor: " + requestInterceptor.getClass().getName());
}
}
if (responseInterceptors != null) {
for (HttpConnectionResponseInterceptor responseInterceptor : responseInterceptors) {
props.addResponseInterceptors(responseInterceptor);
logger.config("Added response interceptor: " + responseInterceptor.getClass().getName());
}
}
// if no gsonBuilder has been provided, create a new one
if (gsonBuilder == null) {
gsonBuilder = new GsonBuilder();
logger.config("Using default GSON builder");
} else {
logger.config("Using custom GSON builder");
}
// always register additional TypeAdapaters for derserializing some Cloudant specific
// types before constructing the CloudantClient
gsonBuilder.registerTypeAdapter(DeserializationTypes.SHARDS, new ShardDeserializer()).registerTypeAdapter(DeserializationTypes.INDICES, new IndexDeserializer()).registerTypeAdapter(DeserializationTypes.PERMISSIONS_MAP, new SecurityDeserializer()).registerTypeAdapter(Key.ComplexKey.class, new Key.ComplexKeyDeserializer());
return new CloudantClient(props, gsonBuilder);
}
Aggregations