Java: URL avec HTTPBasic chercher l'authentification
-
20-09-2019 - |
Question
Je fais une authentification simple HTTP et je obtenir un
java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic OGU0ZTc5ODBk(...trimmed from 76 chars...)
(...more password data...)
que je pense est dû me avoir un nom d'utilisateur et mot de passe très longue et l'encodeur enveloppe avec un \n
à 76 caractères. Est-il possible que je peux contourner cela? L'URL ne supporte que HTTP Basic Auth.
Voici mon code:
private class UserPassAuthenticator extends Authenticator {
String user;
String pass;
public UserPassAuthenticator(String user, String pass) {
this.user = user;
this.pass = pass;
}
// This method is called when a password-protected URL is accessed
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass.toCharArray());
}
}
private String fetch(StoreAccount account, String path) throws IOException {
Authenticator.setDefault(new UserPassAuthenticator(account.getCredentials().getLogin(), account.getCredentials().getPassword()));
URL url = new URL("https", account.getStoreUrl().replace("http://", ""), path);
System.out.println(url);
URLConnection urlConn = url.openConnection();
Object o = urlConn.getContent();
if (!(o instanceof String))
throw new IOException("Wrong Content-Type on " + url.toString());
// Remove the authenticator back to the default
Authenticator.setDefault(null);
return (String) o;
}
La solution
Cela semble être un en Java .
Avez-vous essayé d'utiliser les clients HTTP alternatives, telles que la bibliothèque d'Apache?
Ou au lieu d'utiliser l'authentificateur, réglage manuel de l'en-tête?
URL url = new URL("http://www.example.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Basic OGU0ZTc5ODBkABcde....");
La valeur de jeton est encodeBase64. ( "Nom d'utilisateur: Mot de passe")
Autres conseils
Cela fonctionne pour moi.
HttpsURLConnection con = null; con = (HttpsURLConnection) obj.openConnection (); . Chaîne encoding = Base64.getEncoder () ( "encodeToString: Mot de passe" .getBytes (StandardCharsets.UTF_8)); con.setRequestProperty ( "Autorisation", "Basic "+ encoding.replaceAll (" \ n", ""));
Je trouve que le caractère illégal a été causé par « Autorisation: Basic », encodée qui devrait être "Autorisation", "Basic" + codé