client.getParams().setAuthenticationPreemptive(true);
|
Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
client.getState().setCredentials(new AuthScope("myhost", 80, AuthScope.ANY_REALM), defaultcreds);
|
A client SHOULD assume that all paths at or deeper than the depth of the last symbolic element in the path field of the Request-URI also are within the protection space specified by the Basic realm value of the current challenge. A client MAY preemptively send the corresponding Authorization header with requests for resources in that space without receipt of another challenge from the server. Similarly, when a client sends a request to a proxy, it may reuse a userid and password in the Proxy-Authorization header field without receiving another challenge from the proxy server.
|
// To be avoided unless in debug mode
Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
client.getState().setCredentials(AuthScope.ANY, defaultcreds);
|
HttpClient client = new HttpClient();
List authPrefs = new ArrayList(2);
authPrefs.add(AuthPolicy.DIGEST);
authPrefs.add(AuthPolicy.BASIC);
// This will exclude the NTLM authentication scheme
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
|
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
/**
* A simple example that uses HttpClient to perform a GET using Basic
* Authentication. Can be run standalone without parameters.
*
* You need to have JSSE on your classpath for JDK prior to 1.4
*
* @author Michael Becke
*/
public class BasicAuthenticationExample {
/**
* Constructor for BasicAuthenticatonExample.
*/
public BasicAuthenticationExample() {
super();
}
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient();
// pass our credentials to HttpClient, they will only be used for
// authenticating to servers with realm "realm" on the host
// "www.verisign.com", to authenticate against
// an arbitrary realm or host change the appropriate argument to null.
client.getState().setCredentials(
new AuthScope("www.verisign.com", 443, "realm"),
new UsernamePasswordCredentials("username", "password")
);
// create a GET method that reads a file over HTTPS, we're assuming
// that this file requires basic authentication using the realm above.
GetMethod get = new GetMethod("https://www.verisign.com/products/index.html");
// Tell the GET method to automatically handle authentication. The
// method will use any appropriate credentials to handle basic
// authentication requests. Setting this value to false will cause
// any request for authentication to return with a status of 401.
// It will then be up to the client to handle the authentication.
get.setDoAuthentication( true );
try {
// execute the GET
int status = client.executeMethod( get );
// print the status and response
System.out.println(status + "\n" + get.getResponseBodyAsString());
} finally {
// release any connection resources used by the method
get.releaseConnection();
}
}
}
|
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
/**
* <p>A simple example that uses alternate authentication scheme selection
* if several authentication challenges are returned.
* </p>
*
* <p>Per default HttpClient picks the authentication challenge in the following
* order of preference: NTLM, Digest, Basic. In certain cases it may be desirable to
* force the use of a weaker authentication scheme.
* </p>
*
* @author Oleg Kalnichevski
*/
public class AlternateAuthenticationExample {
/**
* Constructor for BasicAuthenticatonExample.
*/
public AlternateAuthenticationExample() {
super();
}
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient();
client.getState().setCredentials(
new AuthScope("myhost", 80, "myrealm"),
new UsernamePasswordCredentials("username", "password"));
// Suppose the site supports several authetication schemes: NTLM and Basic
// Basic authetication is considered inherently insecure. Hence, NTLM authentication
// is used per default
// This is to make HttpClient pick the Basic authentication scheme over NTLM & Digest
List<String> authPrefs = new ArrayList<String>(3);
authPrefs.add(AuthPolicy.BASIC);
authPrefs.add(AuthPolicy.NTLM);
authPrefs.add(AuthPolicy.DIGEST);
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
GetMethod httpget = new GetMethod("http://myhost/protected/auth-required.html");
try {
int status = client.executeMethod(httpget);
// print the status and response
System.out.println(status);
System.out.println(httpget.getStatusLine());
System.out.println(httpget.getResponseBodyAsString());
} finally {
// release any connection resources used by the method
httpget.releaseConnection();
}
}
}
|
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.commons.httpclient.auth.AuthScheme;
import org.apache.commons.httpclient.auth.AuthenticationException;
import org.apache.commons.httpclient.auth.MalformedChallengeException;
import org.apache.commons.httpclient.params.DefaultHttpParams;
import org.apache.commons.httpclient.params.HttpParams;
/**
* A simple custom AuthScheme example. The included auth scheme is meant
* for demonstration purposes only. It does not actually implement a usable
* authentication method.
*/
public class CustomAuthenticationExample {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// register the auth scheme
AuthPolicy.registerAuthScheme(SecretAuthScheme.NAME, SecretAuthScheme.class);
// include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference,
// this can be done on a per-client or per-method basis but we'll do it
// globally for this example
HttpParams params = DefaultHttpParams.getDefaultParams();
ArrayList<String> schemes = new ArrayList<String>();
schemes.add(SecretAuthScheme.NAME);
schemes.addAll( (Collection) params.getParameter(AuthPolicy.AUTH_SCHEME_PRIORITY));
params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes);
// now that our scheme has been registered we can execute methods against
// servers that require "Secret" authentication...
}
/**
* A custom auth scheme that just uses "Open Sesame" as the authentication
* string.
*/
private class SecretAuthScheme implements AuthScheme {
public static final String NAME = "Secret";
public SecretAuthScheme() {
// All auth schemes must have a no arg constructor.
}
public String authenticate(Credentials credentials, HttpMethod method)
throws AuthenticationException {
return "Open Sesame";
}
public String authenticate(Credentials credentials, String method,
String uri) throws AuthenticationException {
return "Open Sesame";
}
public String getID() {
return NAME;
}
public String getParameter(String name) {
// this scheme does not use parameters, see RFC2617Scheme for an example
return null;
}
public String getRealm() {
// this scheme does not use realms
return null;
}
public String getSchemeName() {
return NAME;
}
public boolean isConnectionBased() {
return false;
}
public void processChallenge(String challenge)
throws MalformedChallengeException {
// Nothing to do here, this is not a challenge based
// auth scheme. See NTLMScheme for a good example.
}
public boolean isComplete() {
// again we're not a challenge based scheme so this is always true
return true;
}
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScheme;
import org.apache.commons.httpclient.auth.CredentialsNotAvailableException;
import org.apache.commons.httpclient.auth.CredentialsProvider;
import org.apache.commons.httpclient.auth.NTLMScheme;
import org.apache.commons.httpclient.auth.RFC2617Scheme;
import org.apache.commons.httpclient.methods.GetMethod;
/**
* A simple example that uses HttpClient to perform interactive
* authentication.
*
* @author Oleg Kalnichevski
*/
public class InteractiveAuthenticationExample {
/**
* Constructor for InteractiveAuthenticationExample.
*/
public InteractiveAuthenticationExample() {
super();
}
public static void main(String[] args) throws Exception {
InteractiveAuthenticationExample demo = new InteractiveAuthenticationExample();
demo.doDemo();
}
private void doDemo() throws IOException {
HttpClient client = new HttpClient();
client.getParams().setParameter(
CredentialsProvider.PROVIDER, new ConsoleAuthPrompter());
GetMethod httpget = new GetMethod("http://target-host/requires-auth.html");
httpget.setDoAuthentication(true);
try {
// execute the GET
int status = client.executeMethod(httpget);
// print the status and response
System.out.println(status);
System.out.println(httpget.getStatusLine().toString());
System.out.println(httpget.getResponseBodyAsString());
} finally {
// release any connection resources used by the method
httpget.releaseConnection();
}
}
public class ConsoleAuthPrompter implements CredentialsProvider {
private BufferedReader in = null;
public ConsoleAuthPrompter() {
super();
this.in = new BufferedReader(new InputStreamReader(System.in));
}
private String readConsole() throws IOException {
return this.in.readLine();
}
public Credentials getCredentials(
final AuthScheme authscheme,
final String host,
int port,
boolean proxy)
throws CredentialsNotAvailableException
{
if (authscheme == null) {
return null;
}
try{
if (authscheme instanceof NTLMScheme) {
System.out.println(host + ":" + port + " requires Windows authentication");
System.out.print("Enter domain: ");
String domain = readConsole();
System.out.print("Enter username: ");
String user = readConsole();
System.out.print("Enter password: ");
String password = readConsole();
return new NTCredentials(user, password, host, domain);
} else
if (authscheme instanceof RFC2617Scheme) {
System.out.println(host + ":" + port + " requires authentication with the realm '"
+ authscheme.getRealm() + "'");
System.out.print("Enter username: ");
String user = readConsole();
System.out.print("Enter password: ");
String password = readConsole();
return new UsernamePasswordCredentials(user, password);
} else {
throw new CredentialsNotAvailableException("Unsupported authentication scheme: " +
authscheme.getSchemeName());
}
} catch (IOException e) {
throw new CredentialsNotAvailableException(e.getMessage(), e);
}
}
}
}
|