List of usage examples for org.apache.http.auth AUTH WWW_AUTH_RESP
String WWW_AUTH_RESP
To view the source code for org.apache.http.auth AUTH WWW_AUTH_RESP.
Click Source Link
From source file:com.ibm.streamsx.rest.StreamsConnection.java
/** * Gets a response to an HTTP call//from ww w .j av a 2s . co m * * @param inputString * REST call to make * @return response from the inputString * @throws IOException */ String getResponseString(String inputString) throws IOException { String sReturn = ""; Request request = Request.Get(inputString).addHeader(AUTH.WWW_AUTH_RESP, apiKey).useExpectContinue(); Response response = executor.execute(request); HttpResponse hResponse = response.returnResponse(); int rcResponse = hResponse.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == rcResponse) { sReturn = EntityUtils.toString(hResponse.getEntity()); } else if (HttpStatus.SC_NOT_FOUND == rcResponse) { // with a 404 message, we are likely to have a message from Streams // but if not, provide a better message sReturn = EntityUtils.toString(hResponse.getEntity()); if ((sReturn != null) && (!sReturn.equals(""))) { throw RESTException.create(rcResponse, sReturn); } else { String httpError = "HttpStatus is " + rcResponse + " for url " + inputString; throw new RESTException(rcResponse, httpError); } } else { // all other errors... String httpError = "HttpStatus is " + rcResponse + " for url " + inputString; throw new RESTException(rcResponse, httpError); } traceLog.finest("Request: " + inputString); traceLog.finest(rcResponse + ": " + sReturn); return sReturn; }
From source file:org.callimachusproject.client.HttpAuthenticator.java
public boolean needAuthentication(final HttpRoute route, final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { final AuthState targetAuthState = getTargetAuthState(context); final AuthState proxyAuthState = getProxyAuthState(context); HttpHost target = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); if (target == null) { target = route.getTargetHost();// www . j av a2 s. c o m } HttpHost proxy = route.getProxyHost(); if (this.needAuthentication(target, proxy, targetAuthState, proxyAuthState, response, context)) { // discard previous auth headers request.removeHeaders(AUTH.WWW_AUTH_RESP); request.removeHeaders(AUTH.PROXY_AUTH_RESP); return true; } else { return false; } }
From source file:com.soundcloud.playerapi.OAuth2Scheme.java
static String extractToken(Header h) { if (h == null || h.getValue() == null) return null; if (AUTH.WWW_AUTH_RESP.equalsIgnoreCase(h.getName())) { Matcher m = AUTHORIZATION_HEADER_PATTERN.matcher(h.getValue()); return m.matches() ? m.group(1) : null; } else {// w w w.ja va 2 s . c o m return null; } }
From source file:com.intel.cosbench.api.httpauth.HttpAuth.java
private void dumpResponse(HttpResponse response) { try {/*from ww w. j a v a 2s .co m*/ System.out.println("\nStatus Line"); System.out.println("-----------"); System.out.println(response.getStatusLine()); Header authHeader = response.getFirstHeader(AUTH.WWW_AUTH); System.out.println("Auth Header = " + authHeader); Header authRspHeader = response.getFirstHeader(AUTH.WWW_AUTH_RESP); System.out.println("Auth Rsp Header = " + authRspHeader); System.out.println("\nHeaders"); System.out.println("-------"); for (Header header : response.getAllHeaders()) { System.out.println(header.toString()); } System.out.println("\nBody"); System.out.println("----"); System.out.println(EntityUtils.toString(response.getEntity())); EntityUtils.consume(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } }
From source file:freeipa.client.negotiation.JBossNegotiateScheme.java
/** * Produces Negotiate authorization Header based on token created by processChallenge. * * @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials * from JAAS will be used instead. * @param request The request being authenticated * * @throws AuthenticationException if authorization string cannot be generated due to an authentication failure * * @return an Negotiate authorization Header *///ww w .java2 s . c o m @Override public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (state != State.CHALLENGE_RECEIVED) { throw new IllegalStateException("Negotiation authentication process has not been initiated"); } try { String key = null; if (isProxy()) { key = ExecutionContext.HTTP_PROXY_HOST; } else { key = ExecutionContext.HTTP_TARGET_HOST; } HttpHost host = (HttpHost) context.getAttribute(key); if (host == null) { throw new AuthenticationException("Authentication host is not set " + "in the execution context"); } String authServer; if (!this.stripPort && host.getPort() > 0) { authServer = host.toHostString(); } else { authServer = host.getHostName(); } System.out.println("init " + authServer); final Oid negotiationOid = new Oid(SPNEGO_OID); final GSSManager manager = GSSManager.getInstance(); final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE); final GSSContext gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); if (token == null) { token = new byte[0]; } token = gssContext.initSecContext(token, 0, token.length); if (token == null) { state = State.FAILED; throw new AuthenticationException("GSS security context initialization failed"); } state = State.TOKEN_GENERATED; String tokenstr = new String(base64codec.encode(token)); System.out.println("Sending response '" + tokenstr + "' back to the auth server"); CharArrayBuffer buffer = new CharArrayBuffer(32); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Negotiate "); buffer.append(tokenstr); return new BufferedHeader(buffer); } catch (GSSException gsse) { state = State.FAILED; if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) throw new InvalidCredentialsException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.NO_CRED) throw new InvalidCredentialsException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN) throw new AuthenticationException(gsse.getMessage(), gsse); // other error throw new AuthenticationException(gsse.getMessage()); } }
From source file:org.ligoj.app.plugin.security.fortify.FortifyPluginResource.java
private String getFortifyToken(final String url, final String user, final String password, final FortifyCurlProcessor processor) { // Use the preempted authentication processor processor.setFortifyToken(null);// w w w . j a va 2s . com final CurlRequest request = new CurlRequest("GET", StringUtils.appendIfMissing(url, "/") + API_TOKEN, null, "Accept:application/json", AUTH.WWW_AUTH_RESP + ":Basic " + BASE64_CODEC.encodeToString((user + ':' + password).getBytes(StandardCharsets.UTF_8))); request.setSaveResponse(true); if (!processor.process(request)) { return null; } // Get the token. final Pattern pattern = Pattern.compile("\"token\"\\s*:\\s*\"([^\"]+)\""); final Matcher matcher = pattern.matcher(request.getResponse()); if (!matcher.find()) { // Something goes wrong return null; } return matcher.group(1); }
From source file:net.community.chest.gitcloud.facade.frontend.git.GitController.java
String authenticate(HttpServletRequest req) throws IOException { Principal principal = req.getUserPrincipal(); // check if already authenticated String username = (principal == null) ? null : principal.getName(); if (!StringUtils.isEmpty(username)) { if (logger.isDebugEnabled()) { logger.debug("authenticate(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]" + " using principal=" + username); }/* ww w . j a v a 2 s. c o m*/ return username; } // TODO try to authenticate by cookie (if feature allowed) - see GitBlit#authenticate String authorization = StringUtils.trimToEmpty(req.getHeader(AUTH.WWW_AUTH_RESP)); if (StringUtils.isEmpty(authorization)) { if (logger.isDebugEnabled()) { logger.debug("authenticate(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "] no authorization data"); } return null; } // TODO add support for more authorization schemes - including password-less HTTP if (!authorization.startsWith(AuthSchemes.BASIC)) { logger.warn("authenticate(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]" + " unsupported authentication scheme: " + authorization); return null; } String b64Credentials = authorization.substring(AuthSchemes.BASIC.length()).trim(); byte[] credBytes = Base64.decodeBase64(b64Credentials); String credentials = new String(credBytes, Charset.forName("UTF-8")); String[] credValues = StringUtils.split(credentials, ':'); Validate.isTrue(credValues.length == 2, "Bad " + AuthSchemes.BASIC + " credentials format: %s", credentials); username = StringUtils.trimToEmpty(credValues[0]); String password = StringUtils.trimToEmpty(credValues[1]); if (authenticate(username, password)) { return username; } else { return null; } }
From source file:org.odk.collect.android.utilities.EnhancedDigestScheme.java
/** * Creates digest-response header as defined in RFC2617. * /*from ww w . j a v a2 s . c om*/ * @param credentials * User credentials * * @return The digest-response as String. */ private Header createDigestHeader(final Credentials credentials) throws AuthenticationException { String uri = getParameter("uri"); String realm = getParameter("realm"); String nonce = getParameter("nonce"); String opaque = getParameter("opaque"); String method = getParameter("methodname"); String algorithm = getParameter("algorithm"); if (uri == null) { throw new IllegalStateException("URI may not be null"); } if (realm == null) { throw new IllegalStateException("Realm may not be null"); } if (nonce == null) { throw new IllegalStateException("Nonce may not be null"); } // TODO: add support for QOP_INT int qop = QOP_UNKNOWN; String qoplist = getParameter("qop"); if (qoplist != null) { StringTokenizer tok = new StringTokenizer(qoplist, ","); while (tok.hasMoreTokens()) { String variant = tok.nextToken().trim(); if (variant.equals("auth")) { qop = QOP_AUTH; break; } } } else { qop = QOP_MISSING; } if (qop == QOP_UNKNOWN) { throw new AuthenticationException("None of the qop methods is supported: " + qoplist); } // If an algorithm is not specified, default to MD5. if (algorithm == null) { algorithm = "MD5"; } // If an charset is not specified, default to ISO-8859-1. String charset = getParameter("charset"); if (charset == null) { charset = "ISO-8859-1"; } String digAlg = algorithm; if (digAlg.equalsIgnoreCase("MD5-sess")) { digAlg = "MD5"; } MessageDigest digester; try { digester = createMessageDigest(digAlg); } catch (UnsupportedDigestAlgorithmException ex) { throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg); } String uname = credentials.getUserPrincipal().getName(); String pwd = credentials.getPassword(); if (nonce.equals(this.lastNonce)) { nounceCount++; } else { nounceCount = 1; cnonce = null; lastNonce = nonce; } StringBuilder sb = new StringBuilder(256); Formatter formatter = new Formatter(sb, Locale.US); formatter.format("%08x", nounceCount); String nc = sb.toString(); if (cnonce == null) { cnonce = createCnonce(); } a1 = null; a2 = null; // 3.2.2.2: Calculating digest if (algorithm.equalsIgnoreCase("MD5-sess")) { // H( unq(username-value) ":" unq(realm-value) ":" passwd ) // ":" unq(nonce-value) // ":" unq(cnonce-value) // calculated one per session sb.setLength(0); sb.append(uname).append(':').append(realm).append(':').append(pwd); String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset))); sb.setLength(0); sb.append(checksum).append(':').append(nonce).append(':').append(cnonce); a1 = sb.toString(); } else { // unq(username-value) ":" unq(realm-value) ":" passwd sb.setLength(0); sb.append(uname).append(':').append(realm).append(':').append(pwd); a1 = sb.toString(); } String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset))); if (qop == QOP_AUTH) { // Method ":" digest-uri-value a2 = method + ':' + uri; } else if (qop == QOP_AUTH_INT) { // Method ":" digest-uri-value ":" H(entity-body) // TODO: calculate entity hash if entity is repeatable throw new AuthenticationException("qop-int method is not suppported"); } else { a2 = method + ':' + uri; } String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset))); // 3.2.2.1 String digestValue; if (qop == QOP_MISSING) { sb.setLength(0); sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2); digestValue = sb.toString(); } else { sb.setLength(0); sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':').append(cnonce) .append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth").append(':').append(hasha2); digestValue = sb.toString(); } String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue))); CharArrayBuffer buffer = new CharArrayBuffer(128); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Digest "); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20); params.add(new BasicNameValuePair("username", uname)); params.add(new BasicNameValuePair("realm", realm)); params.add(new BasicNameValuePair("nonce", nonce)); params.add(new BasicNameValuePair("uri", uri)); params.add(new BasicNameValuePair("response", digest)); if (qop != QOP_MISSING) { params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth")); params.add(new BasicNameValuePair("nc", nc)); params.add(new BasicNameValuePair("cnonce", cnonce)); } if (algorithm != null) { params.add(new BasicNameValuePair("algorithm", algorithm)); } if (opaque != null) { params.add(new BasicNameValuePair("opaque", opaque)); } for (int i = 0; i < params.size(); i++) { BasicNameValuePair param = params.get(i); if (i > 0) { buffer.append(", "); } boolean noQuotes = "nc".equals(param.getName()) || "qop".equals(param.getName()); BasicHeaderValueFormatter.DEFAULT.formatNameValuePair(buffer, param, !noQuotes); } return new BufferedHeader(buffer); }
From source file:com.soundcloud.playerapi.ApiWrapper.java
/** Creates an OAuth2 header for the given token */ public static Header createOAuthHeader(Token token) { return new BasicHeader(AUTH.WWW_AUTH_RESP, "OAuth " + (token == null || !token.valid() ? "invalidated" : token.access)); }