List of usage examples for org.apache.commons.httpclient HttpMethod setDoAuthentication
public abstract void setDoAuthentication(boolean paramBoolean);
From source file:org.apache.abdera.protocol.client.util.MethodHelper.java
private static void initHeaders(RequestOptions options, HttpMethod method) { String[] headers = options.getHeaderNames(); for (String header : headers) { Object[] values = options.getHeaders(header); for (Object value : values) { method.addRequestHeader(header, value.toString()); }//from w ww .jav a2s .c o m } String cc = options.getCacheControl(); if (cc != null && cc.length() != 0) method.setRequestHeader("Cache-Control", cc); if (options.getAuthorization() != null) method.setDoAuthentication(false); }
From source file:org.apache.cactus.client.authentication.BasicAuthentication.java
/** * {@inheritDoc}/*from w ww . j ava2s .c om*/ * @see Authentication#configure */ public void configure(HttpState theState, HttpMethod theMethod, WebRequest theRequest, Configuration theConfiguration) { theState.setAuthenticationPreemptive(true); theState.setCredentials(null, null, new UsernamePasswordCredentials(getName(), getPassword())); theMethod.setDoAuthentication(true); }
From source file:org.apache.clerezza.integrationtest.web.performance.Get404.java
@Override public void run() { try {// w w w . j a v a 2 s.c om URL serverURL = new URL(testSubjectUriPrefix + "/foobar"); HttpClient client = new HttpClient(); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); HttpMethod method = new GetMethod(serverURL.toString()); method.setRequestHeader("Accept", "*/*"); method.setDoAuthentication(true); try { int responseCode = client.executeMethod(method); if (responseCode != HttpStatus.SC_NOT_FOUND) { throw new RuntimeException("Get404: unexpected " + "response code: " + responseCode); } } finally { method.releaseConnection(); } } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.apache.directory.fortress.rest.EmTest.java
/** * Add userId, password to HTTP Basic AuthN header. * * @param httpMethod// ww w .j av a 2 s . c om * @param name * @param password */ private static void setMethodHeaders(HttpMethod httpMethod, String name, String password) { if (httpMethod instanceof PostMethod || httpMethod instanceof PutMethod) { httpMethod.setRequestHeader("Content-Type", "application/xml"); httpMethod.setRequestHeader("Accept", "application/xml"); } httpMethod.setDoAuthentication(true); httpMethod.setRequestHeader("Authorization", "Basic " + base64Encode(name + ":" + password)); }
From source file:org.apache.jetspeed.portlets.sso.SSOWebContentPortlet.java
protected byte[] doPreemptiveAuthentication(HttpClient client, HttpMethod method, RenderRequest request, RenderResponse response) {/*from w ww. java2 s .c om*/ byte[] result = super.doPreemptiveAuthentication(client, method, request, response); if (result != null) { // already handled return result; } // System.out.println("SSOWebContentPortlet.doPreemptiveAuthentication..."); PortletPreferences prefs = request.getPreferences(); String type = getSingleSignOnAuthType(prefs); if (type.equalsIgnoreCase(SSO_TYPE_BASIC_PREEMPTIVE)) { // Preemptive, basic authentication String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; // System.out.println("...performing preemptive basic authentication with userName: "+userName+", and password: "+password); method.setDoAuthentication(true); method.getHostAuthState().setPreemptive(); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); // handled! return result; } else if (type.startsWith(SSO_TYPE_FORM)) { try { Boolean formAuth = (Boolean) PortletMessaging.receive(request, FORM_AUTH_STATE); if (formAuth != null) { // already been here, done that return (formAuth.booleanValue() ? result : null); } else { // stop recursion, but assume failure, ...for now PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.FALSE); } String formAction = prefs.getValue(SSO_TYPE_FORM_ACTION_URL, ""); if (formAction == null || formAction.length() == 0) { log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_ACTION_URL + ", action was specified - unable to preemptively authenticate by form."); return null; } String userNameField = prefs.getValue(SSO_TYPE_FORM_USERNAME_FIELD, ""); if (userNameField == null || userNameField.length() == 0) { log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_USERNAME_FIELD + ", username field was specified - unable to preemptively authenticate by form."); return null; } String passwordField = prefs.getValue(SSO_TYPE_FORM_PASSWORD_FIELD, "password"); if (passwordField == null || passwordField.length() == 0) { log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_PASSWORD_FIELD + ", password field was specified - unable to preemptively authenticate by form."); return null; } String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; // get submit method int i = type.indexOf('.'); boolean isPost = i > 0 ? type.substring(i + 1).equalsIgnoreCase("post") : true; // default to post, since it is a form // get parameter map HashMap formParams = new HashMap(); formParams.put(userNameField, new String[] { userName }); formParams.put(passwordField, new String[] { password }); String formArgs = prefs.getValue(SSO_TYPE_FORM_ACTION_ARGS, ""); if (formArgs != null && formArgs.length() > 0) { StringTokenizer iter = new StringTokenizer(formArgs, ";"); while (iter.hasMoreTokens()) { String pair = iter.nextToken(); i = pair.indexOf('='); if (i > 0) formParams.put(pair.substring(0, i), new String[] { pair.substring(i + 1) }); } } // resuse client - in case new cookies get set - but create a new method (for the formAction) String formMethod = (isPost) ? FORM_POST_METHOD : FORM_GET_METHOD; method = getHttpMethod(client, getURLSource(formAction, formParams, request, response), formParams, formMethod, request); // System.out.println("...posting credentials"); result = doHttpWebContent(client, method, 0, request, response); // System.out.println("Result of attempted authorization: "+success); PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.valueOf(result != null)); return result; } catch (Exception ex) { // bad log.error("Form-based authentication failed", ex); } } else if (type.equalsIgnoreCase(SSO_TYPE_URL) || type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) { // set user name and password parameters in the HttpMethod String userNameParam = prefs.getValue(SSO_TYPE_URL_USERNAME_PARAM, ""); if (userNameParam == null || userNameParam.length() == 0) { log.warn("sso.type specified as 'url', but no: " + SSO_TYPE_URL_USERNAME_PARAM + ", username parameter was specified - unable to preemptively authenticate by URL."); return null; } String passwordParam = prefs.getValue(SSO_TYPE_URL_PASSWORD_PARAM, ""); if (passwordParam == null || passwordParam.length() == 0) { log.warn("sso.type specified as 'url', but no: " + SSO_TYPE_URL_PASSWORD_PARAM + ", password parameter was specified - unable to preemptively authenticate by URL."); return null; } String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; if (type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) { Base64 encoder = new Base64(); userName = new String(encoder.encode(userName.getBytes())); password = new String(encoder.encode(password.getBytes())); } // GET and POST accept args differently if (method instanceof PostMethod) { // add POST data PostMethod postMethod = (PostMethod) method; postMethod.addParameter(userNameParam, userName); postMethod.addParameter(passwordParam, password); } else { // augment GET query string NameValuePair[] authPairs = new NameValuePair[] { new NameValuePair(userNameParam, userName), new NameValuePair(passwordParam, password) }; String existingQuery = method.getQueryString(); method.setQueryString(authPairs); if (existingQuery != null && existingQuery.length() > 0) { // augment existing query with new auth query existingQuery = existingQuery + '&' + method.getQueryString(); method.setQueryString(existingQuery); } } return result; } // else System.out.println("...sso.type: "+type+", no pre-emptive authentication"); // not handled return null; }
From source file:org.apache.jetspeed.portlets.sso.SSOWebContentPortlet.java
protected boolean doRequestedAuthentication(HttpClient client, HttpMethod method, RenderRequest request, RenderResponse response) {//from www .j av a 2s. c o m if (super.doRequestedAuthentication(client, method, request, response)) { // already handled return true; } // System.out.println("SSOWebContentPortlet.doRequestedAuthentication..."); if (method.getHostAuthState().getAuthScheme().getSchemeName().equals(BASIC_AUTH_SCHEME_NAME)) { // Basic authentication being requested String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; // System.out.println("...providing basic authentication with userName: "+userName+", and password: "+password); method.setDoAuthentication(true); AuthState state = method.getHostAuthState(); AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, state.getRealm(), state.getAuthScheme().getSchemeName()); client.getState().setCredentials(scope, new UsernamePasswordCredentials(userName, password)); // handled! return true; } else { log.warn("SSOWebContentPortlent.doAuthenticate() - unexpected authentication scheme: " + method.getHostAuthState().getAuthScheme().getSchemeName()); } // only know how to handle Basic authentication, in this context return false; }
From source file:org.codehaus.httpcache4j.client.HTTPClientResponseResolver.java
@Override protected HTTPResponse resolveImpl(HTTPRequest request) throws IOException { HttpMethod method = convertRequest(request); method.setDoAuthentication(true); client.executeMethod(method);//from w w w . j av a 2 s . co m return convertResponse(method); }
From source file:org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection.java
private HttpMethod createMethod(RequestMethod method, String uri, InputStream data) throws ConnectionException { uri = prepend_base(uri);/*from www.j a va 2 s. c o m*/ if (uri == null) throw new ConnectionException("URI must not be null"); // Extract QP's int qp_start = uri.indexOf('?'); String qps = null; if (qp_start != -1) { qps = uri.substring(qp_start + 1); uri = uri.substring(0, qp_start); } HttpMethod out = null; switch (method) { case POST: { out = new PostMethod(uri); if (data != null) ((PostMethod) out).setRequestEntity(new InputStreamRequestEntity(data)); break; } case PUT: { out = new PutMethod(uri); if (data != null) ((PutMethod) out).setRequestEntity(new InputStreamRequestEntity(data)); break; } case GET: out = new GetMethod(uri); break; case DELETE: out = new DeleteMethod(uri); break; default: throw new ConnectionException("Unsupported method " + method, 0, uri); } if (qps != null) out.setQueryString(qps); out.setDoAuthentication(true); return out; }
From source file:org.devproof.portal.module.bookmark.service.SynchronizeServiceImpl.java
@Override public DeliciousBean getDataFromDelicious(String username, String password, String tags) { logger.debug("Retrieve data from delicious"); HttpClient httpClient = new HttpClient(); HttpClientParams httpClientParams = new HttpClientParams(); DefaultHttpMethodRetryHandler defaultHttpMethodRetryHandler = new DefaultHttpMethodRetryHandler(0, false); httpClientParams.setParameter("User-Agent", BookmarkConstants.USER_AGENT); httpClientParams.setParameter(HttpClientParams.RETRY_HANDLER, defaultHttpMethodRetryHandler); httpClient.setParams(httpClientParams); httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); String urlTag = ""; if (StringUtils.isNotEmpty(tags)) { urlTag = "tag=" + tags; }/* ww w .j a v a2 s .co m*/ HttpMethod method = new GetMethod(BookmarkConstants.DELICIOUS_API + urlTag); method.setDoAuthentication(true); DeliciousBean bean = new DeliciousBean(); try { int httpCode = httpClient.executeMethod(method); bean.setHttpCode(httpCode); if (!bean.hasError()) { XStream xstream = new XStream(new DomDriver()); xstream.alias("posts", DeliciousBean.class); xstream.alias("post", DeliciousPostBean.class); xstream.addImplicitCollection(DeliciousBean.class, "posts"); xstream.useAttributeFor(String.class); xstream.useAttributeFor(Integer.class); bean = (DeliciousBean) xstream.fromXML(method.getResponseBodyAsStream()); bean.setHttpCode(httpCode); } else { bean.setErrorMessage("Unknown Error: Http Status: " + httpCode); } } catch (HttpException e) { bean.setErrorMessage(e.getMessage()); } catch (IOException e) { bean.setErrorMessage(e.getMessage()); } method.releaseConnection(); return bean; }
From source file:org.eclipse.ecf.remoteservice.rest.client.RestClientService.java
protected void setupAuthenticaton(HttpClient httpClient, HttpMethod method) { IConnectContext connectContext = container.getConnectContextForAuthentication(); if (connectContext != null) { NameCallback nameCallback = new NameCallback(""); //$NON-NLS-1$ ObjectCallback passwordCallback = new ObjectCallback(); Callback[] callbacks = new Callback[] { nameCallback, passwordCallback }; CallbackHandler callbackHandler = connectContext.getCallbackHandler(); if (callbackHandler == null) return; try {// www . j ava 2 s .c o m callbackHandler.handle(callbacks); String username = nameCallback.getName(); String password = (String) passwordCallback.getObject(); AuthScope authscope = new AuthScope(null, -1); Credentials credentials = new UsernamePasswordCredentials(username, password); httpClient.getState().setCredentials(authscope, credentials); method.setDoAuthentication(true); } catch (IOException e) { logException("IOException setting credentials for rest httpclient", e); //$NON-NLS-1$ } catch (UnsupportedCallbackException e) { logException("UnsupportedCallbackException setting credentials for rest httpclient", e); //$NON-NLS-1$ } } }