use of org.apache.http.auth.AuthenticationException in project XobotOS by xamarin.
the class DigestScheme method createDigest.
/**
* Creates an MD5 response digest.
*
* @return The created digest as string. This will be the response tag's
* value in the Authentication HTTP header.
* @throws AuthenticationException when MD5 is an unsupported algorithm
*/
private String createDigest(final Credentials credentials) throws AuthenticationException {
// Collecting required tokens
String uri = getParameter("uri");
String realm = getParameter("realm");
String nonce = getParameter("nonce");
String method = getParameter("methodname");
String algorithm = getParameter("algorithm");
if (uri == null) {
throw new IllegalStateException("URI may not be null");
}
if (realm == null) {
throw new IllegalStateException("Realm may not be null");
}
if (nonce == null) {
throw new IllegalStateException("Nonce may not be null");
}
// If an algorithm is not specified, default to MD5.
if (algorithm == null) {
algorithm = "MD5";
}
// If an charset is not specified, default to ISO-8859-1.
String charset = getParameter("charset");
if (charset == null) {
charset = "ISO-8859-1";
}
if (qopVariant == QOP_AUTH_INT) {
throw new AuthenticationException("Unsupported qop in HTTP Digest authentication");
}
MessageDigest md5Helper = createMessageDigest("MD5");
String uname = credentials.getUserPrincipal().getName();
String pwd = credentials.getPassword();
// 3.2.2.2: Calculating digest
StringBuilder tmp = new StringBuilder(uname.length() + realm.length() + pwd.length() + 2);
tmp.append(uname);
tmp.append(':');
tmp.append(realm);
tmp.append(':');
tmp.append(pwd);
// unq(username-value) ":" unq(realm-value) ":" passwd
String a1 = tmp.toString();
//a1 is suitable for MD5 algorithm
if (algorithm.equalsIgnoreCase("MD5-sess")) {
// android-changed: ignore case
// H( unq(username-value) ":" unq(realm-value) ":" passwd )
// ":" unq(nonce-value)
// ":" unq(cnonce-value)
String cnonce = getCnonce();
String tmp2 = encode(md5Helper.digest(EncodingUtils.getBytes(a1, charset)));
StringBuilder tmp3 = new StringBuilder(tmp2.length() + nonce.length() + cnonce.length() + 2);
tmp3.append(tmp2);
tmp3.append(':');
tmp3.append(nonce);
tmp3.append(':');
tmp3.append(cnonce);
a1 = tmp3.toString();
} else if (!algorithm.equalsIgnoreCase("MD5")) {
// android-changed: ignore case
throw new AuthenticationException("Unhandled algorithm " + algorithm + " requested");
}
String md5a1 = encode(md5Helper.digest(EncodingUtils.getBytes(a1, charset)));
String a2 = null;
if (qopVariant == QOP_AUTH_INT) {
// Unhandled qop auth-int
//we do not have access to the entity-body or its hash
//TODO: add Method ":" digest-uri-value ":" H(entity-body)
} else {
a2 = method + ':' + uri;
}
String md5a2 = encode(md5Helper.digest(EncodingUtils.getAsciiBytes(a2)));
// 3.2.2.1
String serverDigestValue;
if (qopVariant == QOP_MISSING) {
StringBuilder tmp2 = new StringBuilder(md5a1.length() + nonce.length() + md5a2.length());
tmp2.append(md5a1);
tmp2.append(':');
tmp2.append(nonce);
tmp2.append(':');
tmp2.append(md5a2);
serverDigestValue = tmp2.toString();
} else {
String qopOption = getQopVariantString();
String cnonce = getCnonce();
StringBuilder tmp2 = new StringBuilder(md5a1.length() + nonce.length() + NC.length() + cnonce.length() + qopOption.length() + md5a2.length() + 5);
tmp2.append(md5a1);
tmp2.append(':');
tmp2.append(nonce);
tmp2.append(':');
tmp2.append(NC);
tmp2.append(':');
tmp2.append(cnonce);
tmp2.append(':');
tmp2.append(qopOption);
tmp2.append(':');
tmp2.append(md5a2);
serverDigestValue = tmp2.toString();
}
String serverDigest = encode(md5Helper.digest(EncodingUtils.getAsciiBytes(serverDigestValue)));
return serverDigest;
}
use of org.apache.http.auth.AuthenticationException in project XobotOS by xamarin.
the class DefaultRequestDirector method createTunnelToTarget.
// establishConnection
/**
* Creates a tunnel to the target server.
* The connection must be established to the (last) proxy.
* A CONNECT request for tunnelling through the proxy will
* be created and sent, the response received and checked.
* This method does <i>not</i> update the connection with
* information about the tunnel, that is left to the caller.
*
* @param route the route to establish
* @param context the context for request execution
*
* @return <code>true</code> if the tunnelled route is secure,
* <code>false</code> otherwise.
* The implementation here always returns <code>false</code>,
* but derived classes may override.
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {
HttpHost proxy = route.getProxyHost();
HttpHost target = route.getTargetHost();
HttpResponse response = null;
boolean done = false;
while (!done) {
done = true;
if (!this.managedConn.isOpen()) {
this.managedConn.open(route, context, this.params);
}
HttpRequest connect = createConnectRequest(route, context);
String agent = HttpProtocolParams.getUserAgent(params);
if (agent != null) {
connect.addHeader(HTTP.USER_AGENT, agent);
}
connect.addHeader(HTTP.TARGET_HOST, target.toHostString());
AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
AuthScope authScope = this.proxyAuthState.getAuthScope();
Credentials creds = this.proxyAuthState.getCredentials();
if (creds != null) {
if (authScope != null || !authScheme.isConnectionBased()) {
try {
connect.addHeader(authScheme.authenticate(creds, connect));
} catch (AuthenticationException ex) {
if (this.log.isErrorEnabled()) {
this.log.error("Proxy authentication error: " + ex.getMessage());
}
}
}
}
response = requestExec.execute(connect, this.managedConn, context);
int status = response.getStatusLine().getStatusCode();
if (status < 200) {
throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
}
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
this.log.debug("Proxy requested authentication");
Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
try {
processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
break;
}
}
updateAuthState(this.proxyAuthState, proxy, credsProvider);
if (this.proxyAuthState.getCredentials() != null) {
done = false;
// Retry request
if (this.reuseStrategy.keepAlive(response, context)) {
this.log.debug("Connection kept alive");
// Consume response content
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
}
} else {
this.managedConn.close();
}
}
} else {
// Reset proxy auth scope
this.proxyAuthState.setAuthScope(null);
}
}
}
int status = response.getStatusLine().getStatusCode();
if (status > 299) {
// Buffer response content
HttpEntity entity = response.getEntity();
if (entity != null) {
response.setEntity(new BufferedHttpEntity(entity));
}
this.managedConn.close();
throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
}
this.managedConn.markReusable();
// Leave it to derived classes, consider insecure by default here.
return false;
}
use of org.apache.http.auth.AuthenticationException in project XobotOS by xamarin.
the class DefaultRequestDirector method handleResponse.
/**
* Analyzes a response to check need for a followup.
*
* @param roureq the request and route.
* @param response the response to analayze
* @param context the context used for the current request execution
*
* @return the followup request and route if there is a followup, or
* <code>null</code> if the response should be returned as is
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context) throws HttpException, IOException {
HttpRoute route = roureq.getRoute();
HttpHost proxy = route.getProxyHost();
RequestWrapper request = roureq.getRequest();
HttpParams params = request.getParams();
if (HttpClientParams.isRedirecting(params) && this.redirectHandler.isRedirectRequested(response, context)) {
if (redirectCount >= maxRedirects) {
throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
}
redirectCount++;
URI uri = this.redirectHandler.getLocationURI(response, context);
HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
HttpGet redirect = new HttpGet(uri);
HttpRequest orig = request.getOriginal();
redirect.setHeaders(orig.getAllHeaders());
RequestWrapper wrapper = new RequestWrapper(redirect);
wrapper.setParams(params);
HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
if (this.log.isDebugEnabled()) {
this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
}
return newRequest;
}
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {
HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (target == null) {
target = route.getTargetHost();
}
this.log.debug("Target requested authentication");
Map<String, Header> challenges = this.targetAuthHandler.getChallenges(response, context);
try {
processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
return null;
}
}
updateAuthState(this.targetAuthState, target, credsProvider);
if (this.targetAuthState.getCredentials() != null) {
// Re-try the same request via the same route
return roureq;
} else {
return null;
}
} else {
// Reset target auth scope
this.targetAuthState.setAuthScope(null);
}
if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
this.log.debug("Proxy requested authentication");
Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
try {
processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
return null;
}
}
updateAuthState(this.proxyAuthState, proxy, credsProvider);
if (this.proxyAuthState.getCredentials() != null) {
// Re-try the same request via the same route
return roureq;
} else {
return null;
}
} else {
// Reset proxy auth scope
this.proxyAuthState.setAuthScope(null);
}
}
return null;
}
use of org.apache.http.auth.AuthenticationException in project platform_external_apache-http by android.
the class DefaultRequestDirector method processChallenges.
// abortConnection
private void processChallenges(final Map<String, Header> challenges, final AuthState authState, final AuthenticationHandler authHandler, final HttpResponse response, final HttpContext context) throws MalformedChallengeException, AuthenticationException {
AuthScheme authScheme = authState.getAuthScheme();
if (authScheme == null) {
// Authentication not attempted before
authScheme = authHandler.selectScheme(challenges, response, context);
authState.setAuthScheme(authScheme);
}
String id = authScheme.getSchemeName();
Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
if (challenge == null) {
throw new AuthenticationException(id + " authorization challenge expected, but not found");
}
authScheme.processChallenge(challenge);
this.log.debug("Authorization challenge processed");
}
use of org.apache.http.auth.AuthenticationException in project platform_external_apache-http by android.
the class AbstractAuthenticationHandler method selectScheme.
public AuthScheme selectScheme(final Map<String, Header> challenges, final HttpResponse response, final HttpContext context) throws AuthenticationException {
AuthSchemeRegistry registry = (AuthSchemeRegistry) context.getAttribute(ClientContext.AUTHSCHEME_REGISTRY);
if (registry == null) {
throw new IllegalStateException("AuthScheme registry not set in HTTP context");
}
List<?> authPrefs = (List<?>) context.getAttribute(ClientContext.AUTH_SCHEME_PREF);
if (authPrefs == null) {
authPrefs = getAuthPreferences();
}
if (this.log.isDebugEnabled()) {
this.log.debug("Authentication schemes in the order of preference: " + authPrefs);
}
AuthScheme authScheme = null;
for (int i = 0; i < authPrefs.size(); i++) {
String id = (String) authPrefs.get(i);
Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
if (challenge != null) {
if (this.log.isDebugEnabled()) {
this.log.debug(id + " authentication scheme selected");
}
try {
authScheme = registry.getAuthScheme(id, response.getParams());
break;
} catch (IllegalStateException e) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication scheme " + id + " not supported");
// Try again
}
}
} else {
if (this.log.isDebugEnabled()) {
this.log.debug("Challenge for " + id + " authentication scheme not available");
// Try again
}
}
}
if (authScheme == null) {
// If none selected, something is wrong
throw new AuthenticationException("Unable to respond to any of these challenges: " + challenges);
}
return authScheme;
}
Aggregations