private synchronized void checkLocalContext() { if (null != sdkProtocolAdatperCustProvider && null != target) { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate DIGEST scheme object, initialize it and add it to the local auth cache String authType = (String) ThreadLocalHolder.get().getEntities().get("AuthType"); if ("Basic".equals(authType)) { LOGGER.debug("authentication type: basic"); } else { DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("nc", String.valueOf(serverNounceCount++)); digestAuth.overrideParamter("cnonce", UUID.randomUUID().toString().replaceAll("-", "")); digestAuth.overrideParamter("qop", "auth"); authCache.put(target, digestAuth); } // Add AuthCache to the execution context localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); } }
private synchronized void checkLocalContext() { if (null != sdkProtocolAdatperCustProvider && null != target) { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate DIGEST scheme object, initialize it and add it to the local auth cache String authType = (String)ThreadLocalHolder.get().getEntities().get("AuthType"); if ("Basic".equals(authType)) { LOGGER.debug("authentication type: basic"); } else { DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("nc", String.valueOf(serverNounceCount++)); digestAuth.overrideParamter("cnonce", UUID.randomUUID().toString().replaceAll("-", "")); digestAuth.overrideParamter("qop", "auth"); authCache.put(target, digestAuth); } // Add AuthCache to the execution context localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); } }
public void init() throws ClientProtocolException, IOException, JAXBException { if (user != null && pwd != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pwd)); AuthCache authCache = new BasicAuthCache(); DigestScheme digestScheme = new DigestScheme(); digestScheme.overrideParamter("realm", "F!Box SOAP-Auth"); digestScheme.overrideParamter("nonce", Long.toString(new Random().nextLong(), 36)); digestScheme.overrideParamter("qop", "auth"); digestScheme.overrideParamter("nc", "0"); digestScheme.overrideParamter("cnonce", DigestScheme.createCnonce()); authCache.put(targetHost, digestScheme); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); readTR64(); } else { readIGDDESC(); } }
public String postWithDigestAuth(final String url, final String file) { String responseBodyAsString = ""; try (CloseableHttpResponse response = httpClient.execute(targetHost, httpPost(url, MultipartEntityBuilder.create(). addPart("bin", new FileBody(new File(file))).build()), setAuth(targetHost, new DigestScheme()))) { responseBodyAsString = IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")); handler.logOutput("Http status: " + response.getStatusLine().getStatusCode(), true); InstallLog.getInstance().info("Http status: " + response.getStatusLine().getStatusCode()); } catch (IOException e) { final String messageError = "Error calling " + url + ": " + e.getMessage(); handler.emitError(messageError, messageError); InstallLog.getInstance().error(messageError); } return responseBodyAsString; }
public int postWithStringEntity(final String url, final String stringEntity) { int status = 0; try { final HttpPost httPost = httpPost(url, new StringEntity(stringEntity)); httPost.addHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType()); try (CloseableHttpResponse response = httpClient.execute(targetHost, httPost, setAuth(targetHost, new DigestScheme()))) { status = response.getStatusLine().getStatusCode(); handler.logOutput("Http status: " + status, true); InstallLog.getInstance().info("Http status: " + status); } } catch (final IOException ioe) { final String messageError = "Error calling " + url + ": " + ioe.getMessage(); handler.emitError(messageError, messageError); InstallLog.getInstance().error(messageError); } return status; }
private void buildBasicHttpContext() { AuthCache authCache = new BasicAuthCache(); DigestScheme digestScheme = new DigestScheme(); digestScheme.overrideParamter("nc", String.valueOf(serverNounceCount++)); digestScheme.overrideParamter("cnonce", UUID.randomUUID().toString().replaceAll("-", "")); digestScheme.overrideParamter("qop", "auth"); authCache.put(target, digestScheme); localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); }
public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE); if (authState != null) { AuthScheme authScheme = authState.getAuthScheme(); // Stick the auth scheme to the local context, so // we could try to authenticate subsequent requests // preemptively if (authScheme instanceof DigestScheme) { context.setAttribute("preemptive-auth", authScheme); } } }
@Test public void testCredentialsFound() throws Exception { final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy(); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); final HttpHost authhost = new HttpHost("somehost", 80); final HttpClientContext context = HttpClientContext.create(); final Map<String, Header> challenges = new HashMap<String, Header>(); challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"realm1\"")); challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm2\", nonce=\"1234\"")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register("basic", new BasicSchemeFactory()) .register("digest", new DigestSchemeFactory()).build(); context.setAuthSchemeRegistry(authSchemeRegistry); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope("somehost", 80, "realm2"), new UsernamePasswordCredentials("user", "pwd")); context.setCredentialsProvider(credentialsProvider); final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context); Assert.assertNotNull(options); Assert.assertEquals(1, options.size()); final AuthOption option = options.remove(); Assert.assertTrue(option.getAuthScheme() instanceof DigestScheme); }
@Test public void testUnsupportedScheme() throws Exception { final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy(); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); final HttpHost authhost = new HttpHost("somehost", 80); final HttpClientContext context = HttpClientContext.create(); final Map<String, Header> challenges = new HashMap<String, Header>(); challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"realm1\"")); challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm2\", nonce=\"1234\"")); challenges.put("whatever", new BasicHeader(AUTH.WWW_AUTH, "Whatever realm=\"realm3\"")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register("basic", new BasicSchemeFactory()) .register("digest", new DigestSchemeFactory()).build(); context.setAuthSchemeRegistry(authSchemeRegistry); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope("somehost", 80), new UsernamePasswordCredentials("user", "pwd")); context.setCredentialsProvider(credentialsProvider); final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context); Assert.assertNotNull(options); Assert.assertEquals(2, options.size()); final AuthOption option1 = options.remove(); Assert.assertTrue(option1.getAuthScheme() instanceof DigestScheme); final AuthOption option2 = options.remove(); Assert.assertTrue(option2.getAuthScheme() instanceof BasicScheme); }
private AuthCache getAuthCache(AuthenticationType authenticationType, HttpHost target) { AuthCache authCache = new BasicAuthCache(); if (authenticationType == AuthenticationType.BASIC) { authCache.put(target, new BasicScheme()); } else { authCache.put(target, new DigestScheme()); } return authCache; }
private int invokeHTTPRequestWithAuth(HttpHost httpHost, HttpPost httpPost, String contentType, String acceptContentType, String userName, String password) throws ClientProtocolException, IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); if (acceptContentType != null && !acceptContentType.isEmpty()) { httpPost.setHeader(HTTP_HEADERS.Accept.name(), acceptContentType); } if (contentType != null && !contentType.isEmpty()) { httpPost.setHeader("Content-Type", contentType); } httpClient.getCredentialsProvider().setCredentials( new AuthScope(httpHost.getHostName(), httpHost.getPort()), new UsernamePasswordCredentials(userName, password)); AuthCache authCache = new BasicAuthCache(); DigestScheme digestScheme = new DigestScheme(); digestScheme.overrideParamter("realm", "SPARQL"); // Virtuoso specific // digestScheme.overrideParamter("nonce", new Nonc); authCache.put(httpHost, digestScheme); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // Execute the request HttpResponse response = httpClient.execute(httpHost, httpPost, localcontext); return response.getStatusLine().getStatusCode(); }
private int invokeHTTPDeleteWithAuth(HttpHost httpHost, String url, String userName, String password) throws ClientProtocolException, IOException { HttpDelete httpDelete = new HttpDelete(url); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getCredentialsProvider().setCredentials( new AuthScope(httpHost.getHostName(), httpHost.getPort()), new UsernamePasswordCredentials(userName, password)); AuthCache authCache = new BasicAuthCache(); DigestScheme digestScheme = new DigestScheme(); digestScheme.overrideParamter("realm", "SPARQL"); // Virtuoso specific // digestScheme.overrideParamter("nonce", new Nonc); authCache.put(httpHost, digestScheme); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // Execute the request HttpResponse response = httpClient.execute(httpHost, httpDelete, localcontext); logger.info(Integer.toString(response.getStatusLine().getStatusCode())); return response.getStatusLine().getStatusCode(); }
private HttpContext createHttpContext(URI uri){ AuthCache authCache = new BasicAuthCache(); DigestScheme digestScheme = new DigestScheme(); HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort()); authCache.put(targetHost, digestScheme); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); return localcontext; }
public HttpClientContext preemptive() { AuthCache authCache = new BasicAuthCache(); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", ""); digestAuth.overrideParamter("nonce", ""); // TODO : Add target // authCache.put(target, digestAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); return localContext; }
/** * * @param scheme * @return */ protected AuthScheme identifyScheme(String scheme) { if(new BasicScheme().getSchemeName().equalsIgnoreCase(scheme)) { return new BasicScheme(); } else if (new DigestScheme().getSchemeName().equalsIgnoreCase(scheme)) { return new DigestScheme(); } else { // fallback return new BasicScheme(); } }
public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE); if (authState != null) { AuthScheme authScheme = authState.getAuthScheme(); if (authScheme instanceof DigestScheme) { context.setAttribute("preemptive-auth", authScheme); } } }
/** * Tests if the plugin correctly converts the Digest authentication scheme * @throws Exception if anything goes wrong */ @Test public void convertDigest() throws Exception { Download t = makeProjectAndTask(); t.authScheme("Digest"); assertTrue(t.getAuthScheme() instanceof DigestScheme); }
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials( new AuthScope("localhost", 80), new UsernamePasswordCredentials("username", "password")); BasicHttpContext localcontext = new BasicHttpContext(); // Generate DIGEST scheme object, initialize it and stick it to // the local execution context DigestScheme digestAuth = new DigestScheme(); // Suppose we already know the realm name digestAuth.overrideParamter("realm", "some realm"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); localcontext.setAttribute("preemptive-auth", digestAuth); // Add as the first request interceptor httpclient.addRequestInterceptor(new PreemptiveAuth(), 0); // Add as the last response interceptor httpclient.addResponseInterceptor(new PersistentDigest()); HttpHost targetHost = new HttpHost("localhost", 80, "http"); HttpGet httpget = new HttpGet("/"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("to target: " + targetHost); for (int i = 0; i < 3; i++) { HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); entity.consumeContent(); } } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
public static void main(String[] args) throws Exception { HttpHost target = new HttpHost("httpbin.org", 80, "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials("user", "passwd")); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); try { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate DIGEST scheme object, initialize it and add it to the local // auth cache DigestScheme digestAuth = new DigestScheme(); // Suppose we already know the realm name digestAuth.overrideParamter("realm", "some realm"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); authCache.put(target, digestAuth); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd"); System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target); for (int i = 0; i < 3; i++) { CloseableHttpResponse response = httpclient.execute(target, httpget, localContext); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); } finally { response.close(); } } } finally { httpclient.close(); } }
/** * Obtiene el valor que hay que poner en la cabecera "Authorization" de la request HTTP * @param code c�d * @param headers * @param requestMethod * @param url * @param authUser * @param authPwd * @return */ public static String getAuthorizationHeaderValue(final HttpURLConnection serverConnectionNoAuth, final RequestMethod requestMethod,final String strUrl, final UserCode authUser,final Password authPwd) throws IOException, AuthenticationException, MalformedChallengeException { // A org.apache.http.impl.auth.DigestScheme instance is // what will process the challenge from the web-server final DigestScheme md5Auth = new DigestScheme(); // Validate that we got an HTTP 401 back HttpResponseCode serverNoAuthResponseCode = HttpResponseCode.of(serverConnectionNoAuth.getResponseCode()); if (serverNoAuthResponseCode.is(HttpResponseCode.UNAUTHORIZED)) { if (CollectionUtils.isNullOrEmpty(serverConnectionNoAuth.getHeaderFields())) throw new IllegalStateException("HTTP Headers not received!"); // headers normalization Map<String,String> headersKeys = _normalizeHeadersKeys(serverConnectionNoAuth.getHeaderFields()); if (headersKeys.containsKey("WWW-AUTHENTICATE")) { // [1] Obtener un objeto HttpRequest a partir de la URL y el m�todo (GET/POST/PUT/DELETE) java.net.URL url = null; try { url = new URL(strUrl); } catch (MalformedURLException e1) { throw new IllegalStateException("The url is malformed"); } HttpRequestBase commonsHttpRequest = _commonsHttpClientRequestFrom(requestMethod,url.getPath()); // [2] Generate a solution Authentication header using the username and password. // 2.1 Get the challenge and solve. String challenge = serverConnectionNoAuth.getHeaderFields() .get(headersKeys.get("WWW-AUTHENTICATE")) .get(0); commonsHttpRequest.addHeader(headersKeys.get("WWW-AUTHENTICATE"), challenge); md5Auth.processChallenge(commonsHttpRequest.getHeaders(headersKeys.get("WWW-AUTHENTICATE"))[0]); // 2.2 Compose a Header object for the "Authorization" header Header solution = md5Auth.authenticate(new UsernamePasswordCredentials(authUser.asString(), authPwd.asString()), commonsHttpRequest, new BasicHttpContext()); return solution.getValue(); // the value of the composed Authorization header } throw new IllegalStateException("A 401 response (unauthorized) has been received, but NO WWW-Authenticate header in this response!"); } throw new IllegalStateException("The request is supossed to be authenticated but the server response code was NOT 401 (unauthorized)"); }
@Test public void testInitializationCustomNoSslDigestAuth() throws Exception { Properties props = new Properties(); props.setProperty(WebServicesFetcher.URL_KEY, "http://foo"); props.setProperty(WebServicesFetcher.APP_ID_KEY, "appId"); props.setProperty(WebServicesFetcher.KEYSTORE_FILE_KEY, ""); props.setProperty(WebServicesFetcher.KEYSTORE_PASSWORD_KEY, ""); props.setProperty(WebServicesFetcher.KEY_PASSWORD_KEY, ""); props.setProperty(WebServicesFetcher.TRUSTSTORE_FILE_KEY, ""); props.setProperty(WebServicesFetcher.TRUSTSTORE_PASSWORD_KEY, ""); props.setProperty(WebServicesFetcher.SUPPORTED_PROTOCOLS_KEY, ""); props.setProperty(WebServicesFetcher.HOSTNAME_VERIFIER_SKIP_KEY, ""); props.setProperty(WebServicesFetcher.MAX_CONCURRENT_CONNECTIONS_KEY, "1"); props.setProperty(WebServicesFetcher.VALIDATE_AFTER_INACTIVITY_KEY, "2"); props.setProperty(WebServicesFetcher.CONNECTION_TIMEOUT_KEY, "5000"); props.setProperty(WebServicesFetcher.NAME_SEPARATOR_KEY, "+"); props.setProperty(WebServicesFetcher.HTTP_AUTH_TYPE_KEY, "digest"); props.setProperty(WebServicesFetcher.HTTP_AUTH_USER_KEY, "user"); props.setProperty(WebServicesFetcher.HTTP_AUTH_PASSWORD_KEY, "password"); Configuration conf = createConfig(props); WebServicesFetcher fetcher = new WebServicesFetcher(); try { fetcher.init(conf); Assert.assertNotNull(fetcher.getConfig()); Assert.assertEquals("http://foo", fetcher.getUrl()); Assert.assertEquals("appId", fetcher.getAppId()); Assert.assertEquals(5000, fetcher.getConnectionTimeout()); Assert.assertEquals("+", fetcher.getSeparator()); Assert.assertEquals("digest", fetcher.getHttpAuth()); Assert.assertEquals("user", fetcher.getHttpAuthUser()); Assert.assertEquals("password", fetcher.getHttpAuthPassword()); Assert.assertNotNull(fetcher.getCredentialsProvider()); Assert.assertEquals("user", fetcher.getCredentialsProvider().getCredentials(AuthScope.ANY).getUserPrincipal().getName() ); Assert.assertEquals("password", fetcher.getCredentialsProvider().getCredentials(AuthScope.ANY).getPassword()); Assert.assertTrue(fetcher.getAuthCache().get(new HttpHost(fetcher.getUrl())) instanceof DigestScheme); PoolingHttpClientConnectionManager connectionManager = fetcher.getConnectionManager(); Assert.assertEquals(1, connectionManager.getMaxTotal()); Assert.assertEquals(1, connectionManager.getDefaultMaxPerRoute()); Assert.assertEquals(2, connectionManager.getValidateAfterInactivity()); Assert.assertNull(fetcher.getSslConnectionSocketFactory()); } finally { fetcher.destroy(); } }
public DigestAuthenticator(DigestScheme mDigestScheme, Credentials credentials) { this.mDigestScheme = mDigestScheme; this.mCredentials = credentials; }
@Provides @Singleton public DigestAuthenticator provideDigestAuthenticator(DigestScheme digestScheme, @Nullable Credentials credentials) { return new DigestAuthenticator(digestScheme, credentials); }
@Provides @Singleton public DigestScheme providesDigestScheme() { return new DigestScheme(); }
public static void main(String[] args) throws Exception { HttpHost target = new HttpHost("localhost", 80, "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials("username", "password")); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); try { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate DIGEST scheme object, initialize it and add it to the local // auth cache DigestScheme digestAuth = new DigestScheme(); // Suppose we already know the realm name digestAuth.overrideParamter("realm", "some realm"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); authCache.put(target, digestAuth); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); HttpGet httpget = new HttpGet("/"); System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target); for (int i = 0; i < 3; i++) { CloseableHttpResponse response = httpclient.execute(target, httpget, localContext); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } } finally { httpclient.close(); } }
public static void main(String[] args) throws Exception { HttpHost targetHost = new HttpHost("localhost", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("username", "password")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate DIGEST scheme object, initialize it and add it to the local // auth cache DigestScheme digestAuth = new DigestScheme(); // Suppose we already know the realm name digestAuth.overrideParamter("realm", "some realm"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); authCache.put(targetHost, digestAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpGet httpget = new HttpGet("/"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("to target: " + targetHost); for (int i = 0; i < 3; i++) { HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } EntityUtils.consume(entity); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
/*** * Creates a apache HTTP Client object, ignoring SSL Exceptions like self signed * certificates and sets Auth. Scheme to Digest Auth * * @param fboxUrl * the URL from config file of fbox to connect to * @return the ready-to-use httpclient for tr064 requests */ private CloseableHttpClient createTr064HttpClient(String fboxUrl) { CloseableHttpClient hc = null; // Convert URL String from config in easy explotable URI object URIBuilder uriFbox = null; try { uriFbox = new URIBuilder(fboxUrl); } catch (URISyntaxException e) { logger.error("Invalid FritzBox URL! {}", e.getMessage()); return null; } // Create context of the http client _httpClientContext = HttpClientContext.create(); CookieStore cookieStore = new BasicCookieStore(); _httpClientContext.setCookieStore(cookieStore); // SETUP AUTH // Auth is specific for this target HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme()); // Add digest authentication with username/pw from global config CredentialsProvider credp = new BasicCredentialsProvider(); credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw)); // Create AuthCache instance. Manages authentication based on server response AuthCache authCache = new BasicAuthCache(); // Generate DIGEST scheme object, initialize it and add it to the local auth // cache. Digeste is standard for fbox auth SOAP DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", "HTTPS Access"); // known from fbox specification digestAuth.overrideParamter("nonce", ""); // never known at first request authCache.put(target, digestAuth); // Add AuthCache to the execution context _httpClientContext.setAuthCache(authCache); // SETUP SSL TRUST SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); SSLConnectionSocketFactory sslsf = null; try { sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // accept self signed certs // dont verify hostname against cert CN sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier()); } catch (Exception ex) { logger.error(ex.getMessage()); } // Set timeout values RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000) .setConnectionRequestTimeout(4000).build(); // BUILDER // setup builder with parameters defined before hc = HttpClientBuilder.create().setSSLSocketFactory(sslsf) // set the SSL options which trust every self signed // cert .setDefaultCredentialsProvider(credp) // set auth options using digest .setDefaultRequestConfig(rc) // set the request config specifying timeout .build(); return hc; }
/** * Create cnonce string. * * @return the cnonce */ public static String createCnonce() { return DigestScheme.createCnonce(); }