List of usage examples for org.apache.http.auth AuthProtocolState SUCCESS
AuthProtocolState SUCCESS
To view the source code for org.apache.http.auth AuthProtocolState SUCCESS.
Click Source Link
From source file:org.callimachusproject.client.HttpAuthenticator.java
private boolean isAuthenticationRequested(final HttpHost host, final HttpResponse response, final AuthenticationStrategy authStrategy, final AuthState authState, final HttpContext context) { if (authStrategy.isAuthenticationRequested(host, response, context)) { this.log.debug("Authentication required"); if (authState.getState() == AuthProtocolState.SUCCESS) { authStrategy.authFailed(host, authState.getAuthScheme(), context); }//from w w w.j a v a 2s .com return true; } else { switch (authState.getState()) { case CHALLENGED: case HANDSHAKE: this.log.debug("Authentication succeeded"); authState.setState(AuthProtocolState.SUCCESS); authStrategy.authSucceeded(host, authState.getAuthScheme(), context); break; case SUCCESS: break; default: authState.setState(AuthProtocolState.UNCHALLENGED); } return false; } }
From source file:com.unboundid.scim.sdk.PreemptiveAuthInterceptor.java
/** * Method to update the AuthState in order to preemptively supply the * credentials to the server./*from www .j a v a2 s . co m*/ * * @param host the HttpHost which we're authenticating to * @param authScheme the AuthScheme in use * @param authState the AuthState object from the HttpContext * @param credsProvider the CredentialsProvider which has the username and * password */ private void doPreemptiveAuth(final HttpHost host, final AuthScheme authScheme, final AuthState authState, final CredentialsProvider credsProvider) { final String schemeName = authScheme.getSchemeName(); final AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName); final Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { if ("BASIC".equalsIgnoreCase(schemeName)) { authState.setState(AuthProtocolState.CHALLENGED); } else { authState.setState(AuthProtocolState.SUCCESS); } authState.update(authScheme, creds); } }
From source file:org.apache.http.client.protocol.RequestAuthCache.java
private void doPreemptiveAuth(final HttpHost host, final AuthScheme authScheme, final AuthState authState, final CredentialsProvider credsProvider) { final String schemeName = authScheme.getSchemeName(); if (this.log.isDebugEnabled()) { this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host); }/*from w ww . java 2 s. com*/ final AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName); final Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) { authState.setState(AuthProtocolState.CHALLENGED); } else { authState.setState(AuthProtocolState.SUCCESS); } authState.update(authScheme, creds); } else { this.log.debug("No credentials for preemptive authentication"); } }
From source file:org.apache.http.impl.auth.HttpAuthenticator.java
public boolean isAuthenticationRequested(final HttpHost host, final HttpResponse response, final AuthenticationStrategy authStrategy, final AuthState authState, final HttpContext context) { if (authStrategy.isAuthenticationRequested(host, response, context)) { this.log.debug("Authentication required"); if (authState.getState() == AuthProtocolState.SUCCESS) { authStrategy.authFailed(host, authState.getAuthScheme(), context); }/*ww w .ja va 2 s .c om*/ return true; } else { switch (authState.getState()) { case CHALLENGED: case HANDSHAKE: this.log.debug("Authentication succeeded"); authState.setState(AuthProtocolState.SUCCESS); authStrategy.authSucceeded(host, authState.getAuthScheme(), context); break; case SUCCESS: break; default: authState.setState(AuthProtocolState.UNCHALLENGED); } return false; } }
From source file:org.apache.http.impl.execchain.MainClientExec.java
public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); AuthState targetAuthState = context.getTargetAuthState(); if (targetAuthState == null) { targetAuthState = new AuthState(); context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, targetAuthState); }/* ww w . j a va2s. c om*/ AuthState proxyAuthState = context.getProxyAuthState(); if (proxyAuthState == null) { proxyAuthState = new AuthState(); context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState); } if (request instanceof HttpEntityEnclosingRequest) { Proxies.enhanceEntity((HttpEntityEnclosingRequest) request); } Object userToken = context.getUserToken(); final ConnectionRequest connRequest = connManager.requestConnection(route, userToken); if (execAware != null) { if (execAware.isAborted()) { connRequest.cancel(); throw new RequestAbortedException("Request aborted"); } else { execAware.setCancellable(connRequest); } } final RequestConfig config = context.getRequestConfig(); final HttpClientConnection managedConn; try { final int timeout = config.getConnectionRequestTimeout(); managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS); } catch (final InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new RequestAbortedException("Request aborted", interrupted); } catch (final ExecutionException ex) { Throwable cause = ex.getCause(); if (cause == null) { cause = ex; } throw new RequestAbortedException("Request execution failed", cause); } context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); if (config.isStaleConnectionCheckEnabled()) { // validate connection if (managedConn.isOpen()) { this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); managedConn.close(); } } } final ConnectionHolder connHolder = new ConnectionHolder(this.log, this.connManager, managedConn); try { if (execAware != null) { execAware.setCancellable(connHolder); } HttpResponse response; for (int execCount = 1;; execCount++) { if (execCount > 1 && !Proxies.isRepeatable(request)) { throw new NonRepeatableRequestException( "Cannot retry request " + "with a non-repeatable request entity."); } if (execAware != null && execAware.isAborted()) { throw new RequestAbortedException("Request aborted"); } if (!managedConn.isOpen()) { this.log.debug("Opening connection " + route); try { establishRoute(proxyAuthState, managedConn, route, request, context); } catch (final TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } } final int timeout = config.getSocketTimeout(); if (timeout >= 0) { managedConn.setSocketTimeout(timeout); } if (execAware != null && execAware.isAborted()) { throw new RequestAbortedException("Request aborted"); } if (this.log.isDebugEnabled()) { this.log.debug("Executing request " + request.getRequestLine()); } if (!request.containsHeader(AUTH.WWW_AUTH_RESP)) { if (this.log.isDebugEnabled()) { this.log.debug("Target auth state: " + targetAuthState.getState()); } this.authenticator.generateAuthResponse(request, targetAuthState, context); } if (!request.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) { if (this.log.isDebugEnabled()) { this.log.debug("Proxy auth state: " + proxyAuthState.getState()); } this.authenticator.generateAuthResponse(request, proxyAuthState, context); } response = requestExecutor.execute(request, managedConn, context); // The connection is in or can be brought to a re-usable state. if (reuseStrategy.keepAlive(response, context)) { // Set the idle duration of this connection final long duration = keepAliveStrategy.getKeepAliveDuration(response, context); if (this.log.isDebugEnabled()) { final String s; if (duration > 0) { s = "for " + duration + " " + TimeUnit.MILLISECONDS; } else { s = "indefinitely"; } this.log.debug("Connection can be kept alive " + s); } connHolder.setValidFor(duration, TimeUnit.MILLISECONDS); connHolder.markReusable(); } else { connHolder.markNonReusable(); } if (needAuthentication(targetAuthState, proxyAuthState, route, response, context)) { // Make sure the response body is fully consumed, if present final HttpEntity entity = response.getEntity(); if (connHolder.isReusable()) { EntityUtils.consume(entity); } else { managedConn.close(); if (proxyAuthState.getState() == AuthProtocolState.SUCCESS && proxyAuthState.getAuthScheme() != null && proxyAuthState.getAuthScheme().isConnectionBased()) { this.log.debug("Resetting proxy auth state"); proxyAuthState.reset(); } if (targetAuthState.getState() == AuthProtocolState.SUCCESS && targetAuthState.getAuthScheme() != null && targetAuthState.getAuthScheme().isConnectionBased()) { this.log.debug("Resetting target auth state"); targetAuthState.reset(); } } // discard previous auth headers final HttpRequest original = request.getOriginal(); if (!original.containsHeader(AUTH.WWW_AUTH_RESP)) { request.removeHeaders(AUTH.WWW_AUTH_RESP); } if (!original.containsHeader(AUTH.PROXY_AUTH_RESP)) { request.removeHeaders(AUTH.PROXY_AUTH_RESP); } } else { break; } } if (userToken == null) { userToken = userTokenHandler.getUserToken(context); context.setAttribute(HttpClientContext.USER_TOKEN, userToken); } if (userToken != null) { connHolder.setState(userToken); } // check for entity, release connection if possible final HttpEntity entity = response.getEntity(); if (entity == null || !entity.isStreaming()) { // connection not needed and (assumed to be) in re-usable state connHolder.releaseConnection(); return Proxies.enhanceResponse(response, null); } else { return Proxies.enhanceResponse(response, connHolder); } } catch (final ConnectionShutdownException ex) { final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down"); ioex.initCause(ex); throw ioex; } catch (final HttpException ex) { connHolder.abortConnection(); throw ex; } catch (final IOException ex) { connHolder.abortConnection(); throw ex; } catch (final RuntimeException ex) { connHolder.abortConnection(); throw ex; } }
From source file:org.apache.http.impl.nio.client.DefaultAsyncRequestDirector.java
@Override public synchronized void responseCompleted(final HttpContext context) { if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + this.id + "] Response fully read"); }/*from ww w. j ava 2 s . c o m*/ try { if (this.resultCallback.isDone()) { return; } if (this.managedConn.isOpen()) { final long duration = this.keepaliveStrategy.getKeepAliveDuration(this.currentResponse, this.localContext); if (this.log.isDebugEnabled()) { final String s; if (duration > 0) { s = "for " + duration + " " + TimeUnit.MILLISECONDS; } else { s = "indefinitely"; } this.log.debug("[exchange: " + this.id + "] Connection can be kept alive " + s); } this.managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS); } else { if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + this.id + "] Connection cannot be kept alive"); } this.managedConn.unmarkReusable(); if (this.proxyAuthState.getState() == AuthProtocolState.SUCCESS && this.proxyAuthState.getAuthScheme() != null && this.proxyAuthState.getAuthScheme().isConnectionBased()) { if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + this.id + "] Resetting proxy auth state"); } this.proxyAuthState.reset(); } if (this.targetAuthState.getState() == AuthProtocolState.SUCCESS && this.targetAuthState.getAuthScheme() != null && this.targetAuthState.getAuthScheme().isConnectionBased()) { if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + this.id + "] Resetting target auth state"); } this.targetAuthState.reset(); } } if (this.finalResponse != null) { this.responseConsumer.responseCompleted(this.localContext); if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + this.id + "] Response processed"); } releaseConnection(); final T result = this.responseConsumer.getResult(); final Exception ex = this.responseConsumer.getException(); if (ex == null) { this.resultCallback.completed(result, this); } else { this.resultCallback.failed(ex, this); } } else { if (this.followup != null) { final HttpRoute actualRoute = this.mainRequest.getRoute(); final HttpRoute newRoute = this.followup.getRoute(); if (!actualRoute.equals(newRoute)) { releaseConnection(); } this.mainRequest = this.followup; } if (this.managedConn != null && !this.managedConn.isOpen()) { releaseConnection(); } if (this.managedConn != null) { this.managedConn.requestOutput(); } else { requestConnection(); } } this.followup = null; this.currentRequest = null; this.currentResponse = null; } catch (final RuntimeException runex) { failed(runex); throw runex; } }
From source file:org.apache.http.impl.nio.client.MainClientExec.java
@Override public void responseCompleted(final InternalState state, final AbstractClientExchangeHandler<?> handler) throws IOException, HttpException { final HttpClientContext localContext = state.getLocalContext(); final HttpResponse currentResponse = handler.getCurrentResponse(); if (!handler.isRouteEstablished()) { final int status = currentResponse.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { handler.setCurrentResponse(null); return; }/* www . ja va 2 s . c om*/ } final boolean keepAlive = handler.manageConnectionPersistence(); if (!keepAlive) { handler.releaseConnection(); final AuthState proxyAuthState = localContext.getProxyAuthState(); if (proxyAuthState.getState() == AuthProtocolState.SUCCESS && proxyAuthState.getAuthScheme() != null && proxyAuthState.getAuthScheme().isConnectionBased()) { if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Resetting proxy auth state"); } proxyAuthState.reset(); } final AuthState targetAuthState = localContext.getTargetAuthState(); if (targetAuthState.getState() == AuthProtocolState.SUCCESS && targetAuthState.getAuthScheme() != null && targetAuthState.getAuthScheme().isConnectionBased()) { if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Resetting target auth state"); } targetAuthState.reset(); } } Object userToken = localContext.getUserToken(); if (userToken == null) { userToken = this.userTokenHandler.getUserToken(localContext); localContext.setAttribute(HttpClientContext.USER_TOKEN, userToken); } if (state.getFinalResponse() != null) { final HttpAsyncResponseConsumer<?> responseConsumer = state.getResponseConsumer(); responseConsumer.responseCompleted(localContext); if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Response processed"); } handler.releaseConnection(); } else { if (state.getRedirect() != null) { final HttpUriRequest redirect = state.getRedirect(); final URI uri = redirect.getURI(); if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Redirecting to '" + uri + "'"); } state.setRedirect(null); final HttpHost newTarget = URIUtils.extractHost(uri); if (newTarget == null) { throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri); } // Reset auth states if redirecting to another host final HttpRoute route = handler.getRoute(); if (!route.getTargetHost().equals(newTarget)) { final AuthState targetAuthState = localContext.getTargetAuthState(); if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Resetting target auth state"); } targetAuthState.reset(); final AuthState proxyAuthState = localContext.getProxyAuthState(); final AuthScheme authScheme = proxyAuthState.getAuthScheme(); if (authScheme != null && authScheme.isConnectionBased()) { if (this.log.isDebugEnabled()) { this.log.debug("[exchange: " + state.getId() + "] Resetting proxy auth state"); } proxyAuthState.reset(); } } if (!redirect.headerIterator().hasNext()) { final HttpRequest original = state.getMainRequest().getOriginal(); redirect.setHeaders(original.getAllHeaders()); } final HttpRequestWrapper newRequest = HttpRequestWrapper.wrap(redirect); final HttpRoute newRoute = this.routePlanner.determineRoute(newTarget, newRequest, localContext); if (!route.equals(newRoute)) { handler.releaseConnection(); } handler.setRoute(newRoute); handler.setCurrentRequest(newRequest); state.setMainRequest(newRequest); prepareRequest(state, handler); } } handler.setCurrentResponse(null); }