List of usage examples for org.apache.http.impl.auth DigestScheme DigestScheme
public DigestScheme()
From source file:securitydigest.TestDigestScheme.java
/** * Test digest authentication using the MD5-sess algorithm. */// w w w.j ava 2 s . c o m public void testDigestAuthenticationMD5SessNoQop() 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"; 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); 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")); assertTrue(null == table.get("nc")); assertEquals("SomeString", table.get("opaque")); assertTrue(null == table.get("qop")); //@TODO: add better check assertTrue(null != table.get("response")); }
From source file:securitydigest.TestDigestScheme.java
/** * Test digest authentication with invalud qop value *///from w ww.j a v a2 s. c o m public void testDigestAuthenticationMD5SessInvalidQop() throws Exception { // Example using Digest auth with MD5-sess String realm = "realm"; String nonce = "e273f1776275974f1a120d8b92c5b3cb"; String challenge = "Digest realm=\"" + realm + "\", " + "nonce=\"" + nonce + "\", " + "opaque=\"SomeString\", " + "stale=false, " + "algorithm=MD5-sess, " + "qop=\"jakarta\""; // jakarta is an invalid qop value Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); try { AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(authChallenge); fail("MalformedChallengeException exception expected due to invalid qop value"); } catch (MalformedChallengeException e) { } }
From source file:securitydigest.TestDigestScheme.java
public void testDigestAuthenticationWithStaleNonce() throws Exception { String challenge = "Digest realm=\"realm1\", " + "nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", stale=\"true\""; Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(authChallenge); assertFalse(authscheme.isComplete()); }
From source file:org.codelibs.fess.es.config.exentity.DataConfig.java
private AuthScheme getAuthScheme(final Map<String, String> paramMap, final String webAuthName, final String scheme) { AuthScheme authScheme = null;/*ww w .ja v a 2 s . c om*/ if (Constants.BASIC.equals(scheme)) { authScheme = new BasicScheme(); } else if (Constants.DIGEST.equals(scheme)) { authScheme = new DigestScheme(); } else if (Constants.NTLM.equals(scheme)) { final Properties props = new Properties(); paramMap.entrySet().stream().filter(e -> e.getKey().startsWith("jcifs.")).forEach(e -> { props.setProperty(e.getKey(), e.getValue()); }); authScheme = new NTLMScheme(new JcifsEngine(props)); } else if (Constants.FORM.equals(scheme)) { final String prefix = CRAWLER_WEB_AUTH + "." + webAuthName + "."; final Map<String, String> parameterMap = paramMap.entrySet().stream() .filter(e -> e.getKey().startsWith(prefix)) .collect(Collectors.toMap(e -> e.getKey().substring(prefix.length()), e -> e.getValue())); authScheme = new FormScheme(parameterMap); } return authScheme; }
From source file:org.jasig.schedassist.impl.caldav.CaldavCalendarDataDaoImpl.java
/** * //from www . java2 s . 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 { throw new IllegalArgumentException("cannot determine AuthScheme implementation from " + scheme); } }
From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java
/** * Execute an auth query using POST/*from w ww . ja v a 2s .c om*/ * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld * @throws Exception */ private JSONObject executeQueryAuthPost(String query, SparqlResultTypes resultType) throws Exception { if (resultType == null) { resultType = getDefaultResultType(); } DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(this.userName, this.password)); String[] serverNoProtocol = this.server.split("://"); //System.err.println("the new server name is: " + serverNoProtocol[1]); HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http"); DigestScheme digestAuth = new DigestScheme(); AuthCache authCache = new BasicAuthCache(); digestAuth.overrideParamter("realm", "SPARQL"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); authCache.put(targetHost, digestAuth); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // add new stuff HttpPost httppost = new HttpPost(getPostURL()); String resultsFormat = this.getContentType(resultType); httppost.addHeader("Accept", resultsFormat); httppost.addHeader("X-Sparql-default-graph", this.dataset); // add params List<NameValuePair> params = new ArrayList<NameValuePair>(3); params.add(new BasicNameValuePair("query", query)); params.add(new BasicNameValuePair("format", resultsFormat)); params.add(new BasicNameValuePair("default-graph-uri", this.dataset)); httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); // finish new stuff HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext); HttpEntity entity = response_http.getEntity(); String responseTxt = EntityUtils.toString(entity, "UTF-8"); // some diagnostic output if (responseTxt == null) { System.err.println("the response text was null!"); } if (responseTxt.trim().isEmpty()) { handleEmptyResponse(); // implementation-specific behavior } JSONObject resp; try { resp = (JSONObject) JSONValue.parse(responseTxt); } catch (Exception e) { entity.getContent().close(); throw new Exception("Cannot parse query result into JSON: " + responseTxt); } if (resp == null) { System.err.println("the response could not be transformed into json"); if (responseTxt.contains("Error")) { entity.getContent().close(); throw new Exception(responseTxt); } entity.getContent().close(); return null; } else { JSONObject procResp = getResultsFromResponse(resp, resultType); entity.getContent().close(); return procResp; } }
From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java
/** * Execute an auth query using POST/*w w w . j a v a2 s .c o m*/ * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld * @throws Exception */ public JSONObject executeAuthUploadOwl(byte[] owl) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(this.userName, this.password)); String[] serverNoProtocol = this.server.split("://"); //System.err.println("the new server name is: " + serverNoProtocol[1]); HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http"); DigestScheme digestAuth = new DigestScheme(); AuthCache authCache = new BasicAuthCache(); digestAuth.overrideParamter("realm", "SPARQL"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); authCache.put(targetHost, digestAuth); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // add new stuff HttpPost httppost = new HttpPost(getUploadURL()); String resultsFormat = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; httppost.addHeader("Accept", resultsFormat); httppost.addHeader("X-Sparql-default-graph", this.dataset); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("graph-uri", this.dataset); builder.addBinaryBody("res-file", owl); HttpEntity entity = builder.build(); httppost.setEntity(entity); /* THIS IS THE MULTIPART FORMAT WE NEED TO SEND. Content-Type: multipart/form-data; boundary=---------------------------32932166721282 Content-Length: 234 -----------------------------32932166721282 Content-Disposition: form-data; name="graph-uri" http://www.kdl.ge.com/changeme -----------------------------32932166721282 Content-Disposition: form-data; name="res-file"; filename="employee.owl" Content-Type: application/octet-stream <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns="http://kdl.ge.com/pd/employee#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" . . . </rdf:RDF> -----------------------------32932166721282-- */ executeTestQuery(); HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext); HttpEntity resp_entity = response_http.getEntity(); // get response with HTML tags removed String responseTxt = EntityUtils.toString(resp_entity, "UTF-8").replaceAll("\\<.*?>", " "); SimpleResultSet ret = new SimpleResultSet(); if (responseTxt.trim().isEmpty()) { // success or bad login :-( ret.setSuccess(true); } else { ret.setSuccess(false); ret.addRationaleMessage(responseTxt); } resp_entity.getContent().close(); return ret.toJson(); }
From source file:de.undercouch.gradle.tasks.download.DownloadAction.java
@Override public void authScheme(Object authScheme) { if (authScheme instanceof AuthScheme) { this.authScheme = (AuthScheme) authScheme; } else if (authScheme instanceof String) { String sa = (String) authScheme; if (sa.equalsIgnoreCase("Basic")) { this.authScheme = new BasicScheme(); } else if (sa.equalsIgnoreCase("Digest")) { this.authScheme = new DigestScheme(); } else {/*from ww w.j a v a 2 s . com*/ throw new IllegalArgumentException( "Invalid authentication scheme: " + "'" + sa + "'. Valid values are 'Basic' and 'Digest'."); } } else { throw new IllegalArgumentException("Invalid authentication " + "scheme. Provide either a String or an instance of " + AuthScheme.class.getName() + "."); } }
From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java
/** * Execute an auth query using GET (use should be rare - in cases where POST is not supported) * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld * @throws Exception/*from w w w. j a va2 s.c o m*/ */ @SuppressWarnings("unused") private JSONObject executeQueryAuthGet(String queryAndUrl, SparqlResultTypes resultType) throws Exception { if (resultType == null) { resultType = getDefaultResultType(); } DefaultHttpClient httpclient = new DefaultHttpClient(); //ResponseHandler<String> responseHandler = new BasicResponseHandler(); System.err.println("the server name was " + this.server); System.err.println("the port id was " + this.port); System.err.println("the user name was " + "SPARQL/" + this.userName); System.err.println("the password was " + this.password); System.err.println(queryAndUrl); httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(this.userName, this.password)); String[] serverNoProtocol = this.server.split("://"); System.err.println("the new server name is: " + serverNoProtocol[1]); HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http"); DigestScheme digestAuth = new DigestScheme(); AuthCache authCache = new BasicAuthCache(); digestAuth.overrideParamter("realm", "SPARQL"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); authCache.put(targetHost, digestAuth); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpGet httpget = new HttpGet(queryAndUrl); String resultsFormat = this.getContentType(resultType); httpget.addHeader("Accept", resultsFormat); System.out.println("executing request" + httpget.getRequestLine()); // String responseTxt = httpclient.execute(httpget, responseHandler); HttpResponse response_http = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response_http.getEntity(); String responseTxt = EntityUtils.toString(entity, "UTF-8"); // some diagnostic output if (responseTxt == null) { System.err.println("the response text was null!"); } if (responseTxt.trim().isEmpty()) { handleEmptyResponse(); // implementation-specific behavior } if (responseTxt.length() < 100) { System.err.println("SparqlEndpointInterface received: " + responseTxt); } else { System.err.println("SparqlEndpointInterface received: " + responseTxt.substring(0, 99) + "... (" + responseTxt.length() + " chars)"); } JSONObject resp; try { resp = (JSONObject) new JSONParser().parse(responseTxt); } catch (Exception e) { throw new Exception("Cannot parse query result into JSON: " + responseTxt); } if (resp == null) { System.err.println("the response could not be transformed into json"); if (responseTxt.contains("Error")) { throw new Exception(responseTxt); } return null; } else { JSONObject procResp = getResultsFromResponse(resp, resultType); return procResp; } }