List of usage examples for org.apache.http.impl.auth DigestScheme DigestScheme
public DigestScheme()
From source file:org.picketbox.test.config.ProtectedResourceManagerUnitTestCase.java
@Test public void testDigestAuth() throws Exception { URL url = new URL(urlStr + "onlyManagers"); DefaultHttpClient httpclient = null; try {//from w ww .j av a 2s .co m String user = "Aladdin"; String pass = "Open Sesame"; httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toExternalForm()); HttpResponse response = httpclient.execute(httpget); assertEquals(401, response.getStatusLine().getStatusCode()); Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); Header header = headers[0]; String value = header.getValue(); value = value.substring(7).trim(); String[] tokens = HTTPDigestUtil.quoteTokenize(value); DigestHolder digestHolder = HTTPDigestUtil.digest(tokens); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("algorithm", "MD5"); digestAuth.overrideParamter("realm", digestHolder.getRealm()); digestAuth.overrideParamter("nonce", digestHolder.getNonce()); digestAuth.overrideParamter("qop", "auth"); digestAuth.overrideParamter("nc", "0001"); digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce()); digestAuth.overrideParamter("opaque", digestHolder.getOpaque()); httpget = new HttpGet(url.toExternalForm()); Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget); System.out.println(auth.getName()); System.out.println(auth.getValue()); httpget.setHeader(auth); System.out.println("executing request" + httpget.getRequestLine()); response = httpclient.execute(httpget); entity = response.getEntity(); System.out.println("----------------------------------------"); StatusLine statusLine = response.getStatusLine(); System.out.println(statusLine); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } assertEquals(404, statusLine.getStatusCode()); 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(); } }
From source file:securitydigest.TestDigestScheme.java
public void testDigestAuthenticationWithSHA() throws Exception { String challenge = "Digest realm=\"realm1\", " + "nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " + "algorithm=SHA"; Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); HttpRequest request = new BasicHttpRequest("Simple", "/"); Credentials cred = new UsernamePasswordCredentials("username", "password"); AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(authChallenge); Header authResponse = authscheme.authenticate(cred, request); Map<String, String> table = parseAuthResponse(authResponse); assertEquals("username", table.get("username")); assertEquals("realm1", table.get("realm")); assertEquals("/", table.get("uri")); assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); assertEquals("8769e82e4e28ecc040b969562b9050580c6d186d", table.get("response")); }
From source file:com.microsoft.exchange.impl.http.CustomHttpComponentsMessageSender.java
/** * //from ww w . j a v a2s . c o m * @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(); } }
From source file:securitydigest.TestDigestScheme.java
public void testDigestAuthenticationWithQueryStringInDigestURI() throws Exception { String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\""; Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); HttpRequest request = new BasicHttpRequest("Simple", "/?param=value"); Credentials cred = new UsernamePasswordCredentials("username", "password"); AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(authChallenge); Header authResponse = authscheme.authenticate(cred, request); Map<String, String> table = parseAuthResponse(authResponse); assertEquals("username", table.get("username")); assertEquals("realm1", table.get("realm")); assertEquals("/?param=value", table.get("uri")); assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); assertEquals("a847f58f5fef0bc087bcb9c3eb30e042", table.get("response")); }
From source file:securitydigest.TestDigestScheme.java
public void testDigestAuthenticationWithMultipleRealms() throws Exception { String challenge1 = "Digest realm=\"realm1\", nonce=\"abcde\""; String challenge2 = "Digest realm=\"realm2\", nonce=\"123546\""; Credentials cred = new UsernamePasswordCredentials("username", "password"); Credentials cred2 = new UsernamePasswordCredentials("uname2", "password2"); Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge1); HttpRequest request = new BasicHttpRequest("Simple", "/"); AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(authChallenge); Header authResponse = authscheme.authenticate(cred, request); Map<String, String> table = parseAuthResponse(authResponse); assertEquals("username", table.get("username")); assertEquals("realm1", table.get("realm")); assertEquals("/", table.get("uri")); assertEquals("abcde", table.get("nonce")); assertEquals("786f500303eac1478f3c2865e676ed68", table.get("response")); authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge2); AuthScheme authscheme2 = new DigestScheme(); authscheme2.processChallenge(authChallenge); authResponse = authscheme2.authenticate(cred2, request); table = parseAuthResponse(authResponse); assertEquals("uname2", table.get("username")); assertEquals("realm2", table.get("realm")); assertEquals("/", table.get("uri")); assertEquals("123546", table.get("nonce")); assertEquals("0283edd9ef06a38b378b3b74661391e9", table.get("response")); }
From source file:SubmitResults.java
public boolean sendFile(Main parent, String hostname, String instanceFilePath, String status, String user, String password, boolean encrypted, String newIdent) { boolean submit_status = false; File tempFile = null;//from w w w . j a va 2s . co m // XSLT if ident needs to be changed final String changeIdXSLT = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" + "<xsl:param name=\"surveyId\"/>" + "<xsl:template match=\"@*|node()\">" + "<xsl:copy>" + "<xsl:apply-templates select=\"@*|node()\"/>" + "</xsl:copy>" + "</xsl:template>" + "<xsl:template match=\"@id\">" + "<xsl:attribute name=\"id\">" + "<xsl:value-of select=\"$surveyId\"/>" + "</xsl:attribute>" + "</xsl:template>" + "</xsl:stylesheet>"; //FileBody fb = null; ContentType ct = null; MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); String urlString = null; HttpHost targetHost = null; if (encrypted) { urlString = "https://" + hostname + "/submission"; targetHost = new HttpHost(hostname, 443, "https"); parent.appendToStatus(" Using https"); //credsProvider.setCredentials( // new AuthScope(hostname, 443, "smap", "digest"), // new UsernamePasswordCredentials(user, password)); credsProvider.setCredentials(new AuthScope(hostname, 443, "smap", "basic"), new UsernamePasswordCredentials(user, password)); } else { urlString = "http://" + hostname + "/submission"; targetHost = new HttpHost(hostname, 80, "http"); parent.appendToStatus(" Using http (not encrypted)"); credsProvider.setCredentials(new AuthScope(hostname, 80, "smap", "digest"), new UsernamePasswordCredentials(user, password)); } CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); // get instance file File instanceFile = new File(instanceFilePath); if (!instanceFile.exists()) { parent.appendToStatus(" Error: Submission file " + instanceFilePath + " does not exist"); } else { HttpPost req = new HttpPost(URI.create(urlString)); //req.setHeader("form_status", status); // smap add form_status header tempFile = populateRequest(parent, status, instanceFilePath, req, changeIdXSLT, ct, entityBuilder, newIdent); // find all files in parent directory /* File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files ignoring invisible files and the submission file List<File> files = new ArrayList<File>(); for (File f : allFiles) { String fileName = f.getName(); if (!fileName.startsWith(".") && !fileName.equals(instanceFile.getName())) { // ignore invisible files and instance xml file files.add(f); } } */ // add the submission file first... /* ct = ContentType.create("text/xml"); //fb = new FileBody(instanceFile, ct); entity.addBinaryBody("xml_submission_file", instanceFile, ct, instanceFile.getPath()); //entity.addPart("xml_submission_file", fb); */ /* for (int j = 0; j < files.size(); j++) { File f = files.get(j); String fileName = f.getName(); int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } // we will be processing every one of these, so // we only need to deal with the content type determination... if (extension.equals("xml")) { ct = ContentType.create("text/xml"); } else if (extension.equals("jpg")) { ct = ContentType.create("image/jpeg"); } else if (extension.equals("3gp")) { ct = ContentType.create("video/3gp"); } else if (extension.equals("3ga")) { ct = ContentType.create("audio/3ga"); } else if (extension.equals("mp4")) { ct = ContentType.create("video/mp4"); } else if (extension.equals("m4a")) { ct = ContentType.create("audio/m4a"); }else if (extension.equals("csv")) { ct = ContentType.create("text/csv"); } else if (f.getName().endsWith(".amr")) { ct = ContentType.create("audio/amr"); } else if (extension.equals("xls")) { ct = ContentType.create("application/vnd.ms-excel"); } else { ct = ContentType.create("application/octet-stream"); parent.appendToStatus(" Info: unrecognised content type for extension " + extension); } //fb = new FileBody(f, ct); //entity.addPart(f.getName(), fb); entity.addBinaryBody(f.getName(), f, ct, f.getName()); parent.appendToStatus(" Info: added file " + f.getName()); } */ //req.setEntity(entity.build()); // prepare response and return uploaded HttpResponse response = null; 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", "smap"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); authCache.put(targetHost, digestAuth); // Generate Basic scheme object BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); parent.appendToStatus(" Info: submitting to: " + req.getURI().toString()); response = httpclient.execute(targetHost, req, localContext); int responseCode = response.getStatusLine().getStatusCode(); try { // have to read the stream in order to reuse the connection InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) ; is.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } // verify that the response was a 201 or 202. // If it wasn't, the submission has failed. parent.appendToStatus(" Info: Response code: " + responseCode + " : " + response.getStatusLine().getReasonPhrase()); if (responseCode != HttpStatus.SC_CREATED && responseCode != HttpStatus.SC_ACCEPTED) { parent.appendToStatus(" Error: upload failed: "); } else { submit_status = true; } } catch (Exception e) { e.printStackTrace(); parent.appendToStatus(" Error: Generic Exception. " + e.toString()); } } try { httpclient.close(); } catch (Exception e) { } finally { } if (tempFile != null) { tempFile.delete(); } return submit_status; }
From source file:org.picketbox.http.test.config.ProtectedResourceManagerUnitTestCase.java
@Test public void testNotAuthorizedResource() throws Exception { URL url = new URL(this.urlStr + "confidentialResource"); DefaultHttpClient httpclient = null; try {// www . java 2 s . c om String user = "Aladdin"; String pass = "Open Sesame"; httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toExternalForm()); HttpResponse response = httpclient.execute(httpget); assertEquals(401, response.getStatusLine().getStatusCode()); Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); Header header = headers[0]; String value = header.getValue(); value = value.substring(7).trim(); String[] tokens = HTTPDigestUtil.quoteTokenize(value); Digest digestHolder = HTTPDigestUtil.digest(tokens); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("algorithm", "MD5"); digestAuth.overrideParamter("realm", digestHolder.getRealm()); digestAuth.overrideParamter("nonce", digestHolder.getNonce()); digestAuth.overrideParamter("qop", "auth"); digestAuth.overrideParamter("nc", "0001"); digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce()); digestAuth.overrideParamter("opaque", digestHolder.getOpaque()); httpget = new HttpGet(url.toExternalForm()); Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget); System.out.println(auth.getName()); System.out.println(auth.getValue()); httpget.setHeader(auth); System.out.println("executing request" + httpget.getRequestLine()); response = httpclient.execute(httpget); entity = response.getEntity(); System.out.println("----------------------------------------"); StatusLine statusLine = response.getStatusLine(); System.out.println(statusLine); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } assertEquals(403, statusLine.getStatusCode()); 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(); } }
From source file:org.picketbox.test.config.ProtectedResourceManagerUnitTestCase.java
@Test public void testNotAuthorizedResource() throws Exception { URL url = new URL(urlStr + "confidentialResource"); DefaultHttpClient httpclient = null; try {//from ww w . j a v a2s . com String user = "Aladdin"; String pass = "Open Sesame"; httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toExternalForm()); HttpResponse response = httpclient.execute(httpget); assertEquals(401, response.getStatusLine().getStatusCode()); Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); Header header = headers[0]; String value = header.getValue(); value = value.substring(7).trim(); String[] tokens = HTTPDigestUtil.quoteTokenize(value); DigestHolder digestHolder = HTTPDigestUtil.digest(tokens); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("algorithm", "MD5"); digestAuth.overrideParamter("realm", digestHolder.getRealm()); digestAuth.overrideParamter("nonce", digestHolder.getNonce()); digestAuth.overrideParamter("qop", "auth"); digestAuth.overrideParamter("nc", "0001"); digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce()); digestAuth.overrideParamter("opaque", digestHolder.getOpaque()); httpget = new HttpGet(url.toExternalForm()); Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget); System.out.println(auth.getName()); System.out.println(auth.getValue()); httpget.setHeader(auth); System.out.println("executing request" + httpget.getRequestLine()); response = httpclient.execute(httpget); entity = response.getEntity(); System.out.println("----------------------------------------"); StatusLine statusLine = response.getStatusLine(); System.out.println(statusLine); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } assertEquals(403, statusLine.getStatusCode()); 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(); } }
From source file:securitydigest.TestDigestScheme.java
/** * Test digest authentication using the MD5-sess algorithm. *//*from w w w. j a va 2s . c om*/ public void testDigestAuthenticationMD5Sess() throws Exception { // Example using Digest auth with MD5-sess String realm = "realm"; String username = "username"; String password = "password"; String nonce = "e273f1776275974f1a120d8b92c5b3cb"; String challenge = "Digest realm=\"" + realm + "\", " + "nonce=\"" + nonce + "\", " + "opaque=\"SomeString\", " + "stale=false, " + "algorithm=MD5-sess, " + "qop=\"auth,auth-int\""; // we pass both but expect auth to be used Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); Credentials cred = new UsernamePasswordCredentials(username, password); HttpRequest request = new BasicHttpRequest("Simple", "/"); AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(authChallenge); Header authResponse = authscheme.authenticate(cred, request); String response = authResponse.getValue(); assertTrue(response.indexOf("nc=00000001") > 0); // test for quotes assertTrue(response.indexOf("qop=auth") > 0); // test for quotes Map<String, String> table = parseAuthResponse(authResponse); assertEquals(username, table.get("username")); assertEquals(realm, table.get("realm")); assertEquals("MD5-sess", table.get("algorithm")); assertEquals("/", table.get("uri")); assertEquals(nonce, table.get("nonce")); assertEquals(1, Integer.parseInt(table.get("nc"), 16)); assertTrue(null != table.get("cnonce")); assertEquals("SomeString", table.get("opaque")); assertEquals("auth", table.get("qop")); //@TODO: add better check assertTrue(null != table.get("response")); }