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 schemes = new ArrayList(); 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... }
public XmlRequest(String host, int port, String protocol) { this.host = host; this.port = port; this.protocol = protocol; setMethod(Method.GET); state.addCookie(cookie); client.setState(state); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.setHostConfiguration(config); List<String> authPrefs = new ArrayList<String>(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); // This will exclude the NTLM authentication scheme client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); }
public static void enableAuth(HttpClient client, Keychain keychain, KeyId keyId) { Signer signer = new Signer(keychain, keyId); CredentialsProvider credProvider = (CredentialsProvider) client.getParams() .getParameter(CredentialsProvider.PROVIDER); CredentialsProvider newProvider; if (credProvider instanceof SignerCredentialsProvider) { newProvider = new SignerCredentialsProvider(signer, ((SignerCredentialsProvider) credProvider).getDelegatee()); } else { newProvider = new SignerCredentialsProvider(signer, credProvider); } client.getParams().setParameter(CredentialsProvider.PROVIDER, newProvider); AuthPolicy.registerAuthScheme(Constants.SCHEME, Http3SignatureAuthScheme.class); List<String> schemes = new ArrayList<String>(); schemes.add(Constants.SCHEME); Collection authSchemePriority = (Collection) DefaultHttpParams.getDefaultParams().getParameter(AuthPolicy.AUTH_SCHEME_PRIORITY); if (authSchemePriority != null) { schemes.addAll(authSchemePriority); } client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes); }
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 authPrefs = new ArrayList(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(httpget.getStatusLine()); System.out.println(httpget.getResponseBodyAsString()); } finally { // release any connection resources used by the method httpget.releaseConnection(); } }
public static void main(String[] args) { // register the auth scheme AuthPolicy.registerAuthScheme("Negotiate", NegotiateScheme.class); // include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference ArrayList schemes = new ArrayList(); schemes.add("Negotiate"); HttpParams params = DefaultHttpParams.getDefaultParams(); params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes); // now that our scheme has been registered we can execute methods against // servers that require "Negotiate" authentication... HttpClient client = new HttpClient(); // The Negotiate scheme uses JAAS as credential provider but the // httpclient api require us to supply cred anyway. // a work around is to provide an empty set of creds. Credentials use_jaas_creds = new Credentials() {}; client.getState().setCredentials( new AuthScope(null, -1, null), use_jaas_creds); GetMethod httpget = new GetMethod(args[0]); try { client.executeMethod(httpget); //System.out.println(httpget.getStatusLine()); //System.out.println(httpget.getResponseBodyAsString()); } catch (Exception e) { e.printStackTrace(); } finally { // release any connection resources used by the method httpget.releaseConnection(); } }
@Override public void applyTo(OwnCloudClient client) { List<String> authPrefs = new ArrayList<String>(1); authPrefs.add(AuthPolicy.BASIC); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials( AuthScope.ANY, new UsernamePasswordCredentials(mUsername, mPassword) ); }
@Override public void applyTo(OwnCloudClient client) { AuthPolicy.registerAuthScheme(BearerAuthScheme.AUTH_POLICY, BearerAuthScheme.class); List<String> authPrefs = new ArrayList<String>(1); authPrefs.add(BearerAuthScheme.AUTH_POLICY); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials( AuthScope.ANY, new BearerCredentials(mAccessToken) ); }
public static void registerNTCredentials(String urlBasePath, String username, String password, String domain) throws MalformedURLException { client.getParams().setAuthenticationPreemptive(true); URL url = new URL(urlBasePath); Core.getLogger("NTLM").info(url.getHost()); Credentials defaultcreds = new NTCredentials(username, password, url.getHost(), domain); AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, restservices.util.JCIFS_NTLMScheme.class); List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.NTLM); client.getParams().setParameter("http.auth.target-scheme-pref", authpref); client.getState().setCredentials(new AuthScope(AuthScope.ANY), defaultcreds); }
/** * Prepare asynchronous connection. * * @throws EWSHttpException * throws EWSHttpException */ public void prepareAsyncConnection() throws EWSHttpException { try { if(trustManger != null) { EwsSSLProtocolSocketFactory.trustManager = trustManger; } Protocol.registerProtocol("https", new Protocol("https", new EwsSSLProtocolSocketFactory(), 443)); AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, EwsJCIFSNTLMScheme.class); client = new HttpClient(this.simpleHttpConnMng); List authPrefs = new ArrayList(); authPrefs.add(AuthPolicy.NTLM); authPrefs.add(AuthPolicy.BASIC); authPrefs.add(AuthPolicy.DIGEST); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); client.getState().setCredentials(AuthScope.ANY, new NTCredentials(getUserName(),getPassword(),"",getDomain())); client.getHttpConnectionManager().getParams().setSoTimeout(getTimeout()); client.getHttpConnectionManager().getParams().setConnectionTimeout(20000); httpMethod = new GetMethod(getUrl().toString()); httpMethod.setFollowRedirects(isAllowAutoRedirect()); int status = client.executeMethod(httpMethod); } catch (IOException e) { client = null; httpMethod = null; throw new EWSHttpException("Unable to open connection to " + this.getUrl()); } }
private static void initNTLMv2() { if (!registeredNTLM) { try { logger.info(" adding NTLMv2 based authentication schema for HttpClient"); AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, com.jivesoftware.authHelper.customescheme.ntlm2.CustomNTLM2Scheme.class); registeredNTLM = true; } catch (Throwable e) { logger.log(java.util.logging.Level.SEVERE, "Could not add NTLM based on JCIFS authentication schema for HttpClient.", e); } } }
private static void initKERBEROS(HttpClient httpClient) { if (!registeredKERBEROS) { try { logger.info("Globally adding KERBEROS "); System.setProperty(USE_SUBJECT_CREDS, "false"); AuthPolicy.registerAuthScheme(NEGOTIATE, com.jivesoftware.authHelper.customescheme.negotiate.CustomNegotiateScheme.class); registeredKERBEROS = true; } catch (Throwable e) { logger.log(java.util.logging.Level.SEVERE, "Could not add KERBEROS for HttpClient.", e); } } }
@Override protected void configureHttpClient(HttpClient client) { super.configureHttpClient(client); if (isUseNTLM()) { client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, Arrays.asList(AuthPolicy.NTLM)); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); Credentials credentials = new NTCredentials(getUsername(), getPassword(), getHost(), getDomain()); client.getState().setCredentials(authScope, credentials); } }
/** * Factory method used by producers and consumers to create a new {@link HttpClient} instance */ public HttpClient createHttpClient() { ObjectHelper.notNull(clientParams, "clientParams"); ObjectHelper.notNull(httpConnectionManager, "httpConnectionManager"); HttpClient answer = new HttpClient(getClientParams()); // configure http proxy from camelContext if (ObjectHelper.isNotEmpty(getCamelContext().getProperty("http.proxyHost")) && ObjectHelper.isNotEmpty(getCamelContext().getProperty("http.proxyPort"))) { String host = getCamelContext().getProperty("http.proxyHost"); int port = Integer.parseInt(getCamelContext().getProperty("http.proxyPort")); LOG.debug("CamelContext properties http.proxyHost and http.proxyPort detected. Using http proxy host: {} port: {}", host, port); answer.getHostConfiguration().setProxy(host, port); } if (getProxyHost() != null) { LOG.debug("Using proxy: {}:{}", getProxyHost(), getProxyPort()); answer.getHostConfiguration().setProxy(getProxyHost(), getProxyPort()); } if (getAuthMethodPriority() != null) { List<String> authPrefs = new ArrayList<String>(); Iterator<?> it = getCamelContext().getTypeConverter().convertTo(Iterator.class, getAuthMethodPriority()); int i = 1; while (it.hasNext()) { Object value = it.next(); AuthMethod auth = getCamelContext().getTypeConverter().convertTo(AuthMethod.class, value); if (auth == null) { throw new IllegalArgumentException("Unknown authMethod: " + value + " in authMethodPriority: " + getAuthMethodPriority()); } LOG.debug("Using authSchemePriority #{}: {}", i, auth); authPrefs.add(auth.name()); i++; } if (!authPrefs.isEmpty()) { answer.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); } } answer.setHttpConnectionManager(httpConnectionManager); HttpClientConfigurer configurer = getHttpClientConfigurer(); if (configurer != null) { configurer.configureHttpClient(answer); } return answer; }
/** * Prepare connection * * @throws EWSHttpException * the eWS http exception */ @Override public void prepareConnection() throws EWSHttpException { if(trustManger != null) { EwsSSLProtocolSocketFactory.trustManager = trustManger; } Protocol.registerProtocol("https", new Protocol("https", new EwsSSLProtocolSocketFactory(), 443)); AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, EwsJCIFSNTLMScheme.class); client = new HttpClient(this.simpleHttpConnMng); List authPrefs = new ArrayList(); authPrefs.add(AuthPolicy.NTLM); authPrefs.add(AuthPolicy.BASIC); authPrefs.add(AuthPolicy.DIGEST); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); if(getProxy() != null) { client.getHostConfiguration().setProxy(getProxy().getHost(),getProxy().getPort()); if (HttpProxyCredentials.isProxySet()) { AuthScope authScope = new AuthScope(getProxy().getHost(), getProxy().getPort()); client.getState().setProxyCredentials(authScope, new NTCredentials(HttpProxyCredentials.getUserName(), HttpProxyCredentials.getPassword(), "",HttpProxyCredentials.getDomain())); //new AuthScope(AuthScope.ANY_HOST, 80, AuthScope.ANY_REALM) } } if(getUserName() != null) { client.getState().setCredentials(AuthScope.ANY, new NTCredentials(getUserName(),getPassword(),"",getDomain())); } client.getHttpConnectionManager().getParams().setSoTimeout(getTimeout()); client.getHttpConnectionManager().getParams().setConnectionTimeout(getTimeout()); httpMethod = new PostMethod(getUrl().toString()); httpMethod.setRequestHeader("Content-type", getContentType()); httpMethod.setDoAuthentication(true); httpMethod.setRequestHeader("User-Agent", getUserAgent()); httpMethod.setRequestHeader("Accept", getAccept()); httpMethod.setRequestHeader("Keep-Alive", "300"); httpMethod.setRequestHeader("Connection", "Keep-Alive"); if(this.cookies !=null && this.cookies.length > 0){ client.getState().addCookies(this.cookies); } //httpMethod.setFollowRedirects(isAllowAutoRedirect()); if (isAcceptGzipEncoding()) { httpMethod.setRequestHeader("Accept-Encoding", "gzip,deflate"); } if (getHeaders().size() > 0){ for (Map.Entry httpHeader : getHeaders().entrySet()) { httpMethod.setRequestHeader((String)httpHeader.getKey(), (String)httpHeader.getValue()); } } }
@Override public synchronized void login() { // exclude the NTLM authentication scheme (requires NTCredentials we don't supply) List<String> authPrefs = new ArrayList<String>(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); // first try Apollo style login String authPoint = pathJoin("/", location, "/authentication-point/alm-authenticate"); String authXml = createAuthXml(); PostMethod post = initPostMethod(authPoint, authXml); ResultInfo resultInfo = ResultInfo.create(null); executeAndWriteResponse(post, resultInfo, Collections.<Integer>emptySet()); if(resultInfo.getHttpStatus() == HttpStatus.SC_NOT_FOUND) { // try Maya style login Credentials cred = new UsernamePasswordCredentials(userName, password); AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); httpClient.getParams().setParameter(HttpMethodParams.CREDENTIAL_CHARSET, "UTF-8"); httpClient.getState().setCredentials(scope, cred); authPoint = pathJoin("/", location, "/authentication-point/authenticate"); GetMethod get = new GetMethod(authPoint); resultInfo = ResultInfo.create(null); executeAndWriteResponse(get, resultInfo, Collections.<Integer>emptySet()); } HttpStatusBasedException.throwForError(resultInfo); if(resultInfo.getHttpStatus() != 200) { // during login we only accept 200 status (to avoid redirects and such as seemingly correct login) throw new AuthenticationFailureException(resultInfo); } Cookie[] cookies = httpClient.getState().getCookies(); Cookie ssoCookie = getSessionCookieByName(cookies, COOKIE_SSO_NAME); addTenantCookie(ssoCookie); //Since ALM 12.00 it is required explicitly ask for QCSession calling "/rest/site-session" //For all the rest of HP ALM / AGM versions it is optional String siteSessionPoint = pathJoin("/", location, "/rest/site-session"); String sessionParamXml = createRestSessionXml(); post = initPostMethod(siteSessionPoint, sessionParamXml); resultInfo = ResultInfo.create(null); executeAndWriteResponse(post, resultInfo, Collections.<Integer>emptySet()); //AGM throws 403 if (resultInfo.getHttpStatus() != HttpStatus.SC_FORBIDDEN) { HttpStatusBasedException.throwForError(resultInfo); } cookies = httpClient.getState().getCookies(); Cookie qcCookie = getSessionCookieByName(cookies, COOKIE_SESSION_NAME); sessionContext = new SessionContext(location, ssoCookie, qcCookie); }