List of usage examples for com.google.common.net HttpHeaders AUTHORIZATION
String AUTHORIZATION
To view the source code for com.google.common.net HttpHeaders AUTHORIZATION.
Click Source Link
From source file:org.jclouds.glacier.util.AWSRequestSignerV4.java
public HttpRequest sign(HttpRequest request) { // Grab the needed data to build the signature Multimap<String, String> canonicalizedHeadersMap = buildCanonicalizedHeadersMap(request); String canonicalizedHeadersString = buildCanonicalizedHeadersString(canonicalizedHeadersMap); String signedHeaders = buildSignedHeaders(canonicalizedHeadersMap); String date = request.getFirstHeaderOrNull(GlacierHeaders.ALTERNATE_DATE); String dateWithoutTimestamp = formatDateWithoutTimestamp(date); String method = request.getMethod(); String endpoint = request.getEndpoint().getRawPath(); String credentialScope = buildCredentialScope(dateWithoutTimestamp); HashCode hashedPayload = buildHashedPayload(request); // Task 1: Create a Canonical Request For Signature Version 4. HashCode hashedCanonicalRequest = buildHashedCanonicalRequest(method, endpoint, hashedPayload, canonicalizedHeadersString, signedHeaders); // Task 2: Create a String to Sign for Signature Version 4. String stringToSign = createStringToSign(date, credentialScope, hashedCanonicalRequest); // Task 3: Calculate the AWS Signature Version 4. String signature = buildSignature(dateWithoutTimestamp, stringToSign); // Sign the request String authHeader = buildAuthHeader(identity, credentialScope, signedHeaders, signature); request = request.toBuilder().replaceHeader(HttpHeaders.AUTHORIZATION, authHeader).build(); return request; }
From source file:com.google.api.auth.Authenticator.java
private static Optional<String> extractAuthToken(HttpServletRequest request) { String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION); if (authHeader != null) { // When the authorization header is present, extract the token from the // header. if (authHeader.startsWith(BEARER_TOKEN_PREFIX)) { return Optional.of(authHeader.substring(BEARER_TOKEN_PREFIX.length())); }//from ww w .j a va 2s . c om return Optional.absent(); } String accessToken = request.getParameter(ACCESS_TOKEN_PARAM_NAME); if (accessToken != null) { return Optional.of(accessToken); } return Optional.absent(); }
From source file:org.jclouds.s3.filters.Aws4SignerForChunkedUpload.java
protected HttpRequest sign(HttpRequest request) throws HttpException { checkNotNull(request, "request is not ready to sign"); checkNotNull(request.getEndpoint(), "request is not ready to sign, request.endpoint not present."); Payload payload = request.getPayload(); // chunked upload required content-length. Long contentLength = payload.getContentMetadata().getContentLength(); // check contentLength not null checkNotNull(contentLength, "request is not ready to sign, payload contentLength not present."); // get host from request endpoint. String host = request.getEndpoint().getHost(); Date date = timestampProvider.get(); String timestamp = timestampFormat.format(date); String datestamp = dateFormat.format(date); String service = serviceAndRegion.service(); String region = serviceAndRegion.region(host); String credentialScope = Joiner.on('/').join(datestamp, region, service, "aws4_request"); HttpRequest.Builder<?> requestBuilder = request.toBuilder() // .removeHeader(AUTHORIZATION) // remove Authorization .removeHeader(DATE) // remove Date .removeHeader(CONTENT_LENGTH); // remove Content-Length ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableSortedMap .<String, String>naturalOrder(); // content-encoding String contentEncoding = CONTENT_ENCODING_HEADER_AWS_CHUNKED; String originalContentEncoding = payload.getContentMetadata().getContentEncoding(); if (originalContentEncoding != null) { contentEncoding += "," + originalContentEncoding; }//from ww w.j ava 2 s .c om requestBuilder.replaceHeader(HttpHeaders.CONTENT_ENCODING, contentEncoding); signedHeadersBuilder.put(HttpHeaders.CONTENT_ENCODING.toLowerCase(), contentEncoding); // x-amz-decoded-content-length requestBuilder.replaceHeader(AMZ_DECODED_CONTENT_LENGTH_HEADER, contentLength.toString()); signedHeadersBuilder.put(AMZ_DECODED_CONTENT_LENGTH_HEADER.toLowerCase(), contentLength.toString()); // how big is the overall request stream going to be once we add the signature // 'headers' to each chunk? long totalLength = calculateChunkedContentLength(contentLength, userDataBlockSize); requestBuilder.replaceHeader(CONTENT_LENGTH, Long.toString(totalLength)); signedHeadersBuilder.put(CONTENT_LENGTH.toLowerCase(), Long.toString(totalLength)); // Content MD5 String contentMD5 = request.getFirstHeaderOrNull(CONTENT_MD5); if (payload != null) { HashCode md5 = payload.getContentMetadata().getContentMD5AsHashCode(); if (md5 != null) { contentMD5 = BaseEncoding.base64().encode(md5.asBytes()); } } if (contentMD5 != null) { requestBuilder.replaceHeader(CONTENT_MD5, contentMD5); signedHeadersBuilder.put(CONTENT_MD5.toLowerCase(), contentMD5); } // Content Type // content-type is not a required signing param. However, examples use this, so we include it to ease testing. String contentType = getContentType(request); if (!Strings.isNullOrEmpty(contentType)) { requestBuilder.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType); signedHeadersBuilder.put(HttpHeaders.CONTENT_TYPE.toLowerCase(), contentType); } else { requestBuilder.removeHeader(HttpHeaders.CONTENT_TYPE); } // host requestBuilder.replaceHeader(HttpHeaders.HOST, host); signedHeadersBuilder.put(HttpHeaders.HOST.toLowerCase(), host); // user-agent, not a required signing param if (request.getHeaders().containsKey(HttpHeaders.USER_AGENT)) { signedHeadersBuilder.put(HttpHeaders.USER_AGENT.toLowerCase(), request.getFirstHeaderOrNull(HttpHeaders.USER_AGENT)); } // all x-amz-* headers appendAmzHeaders(request, signedHeadersBuilder); // x-amz-security-token Credentials credentials = creds.get(); if (credentials instanceof SessionCredentials) { String token = SessionCredentials.class.cast(credentials).getSessionToken(); requestBuilder.replaceHeader(AMZ_SECURITY_TOKEN_HEADER, token); signedHeadersBuilder.put(AMZ_SECURITY_TOKEN_HEADER.toLowerCase(), token); } // x-amz-content-sha256 String contentSha256 = getPayloadHash(); requestBuilder.replaceHeader(AMZ_CONTENT_SHA256_HEADER, contentSha256); signedHeadersBuilder.put(AMZ_CONTENT_SHA256_HEADER.toLowerCase(), contentSha256); // put x-amz-date requestBuilder.replaceHeader(AMZ_DATE_HEADER, timestamp); signedHeadersBuilder.put(AMZ_DATE_HEADER.toLowerCase(), timestamp); ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build(); String stringToSign = createStringToSign(request.getMethod(), request.getEndpoint(), signedHeaders, timestamp, credentialScope, contentSha256); signatureWire.getWireLog().debug("<< " + stringToSign); byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service); // init hmacSHA256 processor for seed signature and chunked block signature ByteProcessor<byte[]> hmacSHA256; try { hmacSHA256 = hmacSHA256(crypto, signatureKey); } catch (InvalidKeyException e) { throw new ChunkedUploadException("invalid key", e); } // Calculating the Seed Signature String signature; try { signature = hex(readBytes(toInputStream(stringToSign), hmacSHA256)); } catch (IOException e) { throw new ChunkedUploadException("hmac sha256 seed signature error", e); } StringBuilder authorization = new StringBuilder(AMZ_ALGORITHM_HMAC_SHA256).append(" "); authorization.append("Credential=").append(Joiner.on("/").join(credentials.identity, credentialScope)) .append(", "); authorization.append("SignedHeaders=").append(Joiner.on(";").join(signedHeaders.keySet())).append(", "); authorization.append("Signature=").append(signature); // replace request payload with chunked upload payload ChunkedUploadPayload chunkedPayload = new ChunkedUploadPayload(payload, userDataBlockSize, timestamp, credentialScope, hmacSHA256, signature); chunkedPayload.getContentMetadata().setContentEncoding(null); return requestBuilder.replaceHeader(HttpHeaders.AUTHORIZATION, authorization.toString()) .payload(chunkedPayload).build(); }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
private void doHandle(HttpServletRequest request, HttpServletResponse response) throws IOException, S3Exception { String method = request.getMethod(); String uri = request.getRequestURI(); logger.debug("request: {}", request); String hostHeader = request.getHeader(HttpHeaders.HOST); if (hostHeader != null && virtualHost.isPresent()) { hostHeader = HostAndPort.fromString(hostHeader).getHostText(); String virtualHostSuffix = "." + virtualHost.get(); if (!hostHeader.equals(virtualHost.get())) { if (hostHeader.endsWith(virtualHostSuffix)) { String bucket = hostHeader.substring(0, hostHeader.length() - virtualHostSuffix.length()); uri = "/" + bucket + uri; } else { String bucket = hostHeader.toLowerCase(); uri = "/" + bucket + uri; }/* ww w . j a v a 2 s . com*/ } } boolean hasDateHeader = false; boolean hasXAmzDateHeader = false; for (String headerName : Collections.list(request.getHeaderNames())) { for (String headerValue : Collections.list(request.getHeaders(headerName))) { logger.trace("header: {}: {}", headerName, Strings.nullToEmpty(headerValue)); } if (headerName.equalsIgnoreCase(HttpHeaders.DATE)) { hasDateHeader = true; } else if (headerName.equalsIgnoreCase("x-amz-date")) { hasXAmzDateHeader = true; } } // anonymous request if (method.equals("GET") && request.getHeader(HttpHeaders.AUTHORIZATION) == null && request.getParameter("AWSAccessKeyId") == null && defaultBlobStore != null) { doHandleAnonymous(request, response, uri, defaultBlobStore); return; } if (!anonymousIdentity && !hasDateHeader && !hasXAmzDateHeader && request.getParameter("Expires") == null) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED, "AWS authentication requires a valid Date or" + " x-amz-date header"); } // TODO: apply sanity checks to X-Amz-Date if (hasDateHeader) { long date; try { date = request.getDateHeader(HttpHeaders.DATE); } catch (IllegalArgumentException iae) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED, iae); } if (date < 0) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED); } long now = System.currentTimeMillis(); if (now + TimeUnit.DAYS.toMillis(1) < date || now - TimeUnit.DAYS.toMillis(1) > date) { throw new S3Exception(S3ErrorCode.REQUEST_TIME_TOO_SKEWED); } } BlobStore blobStore; String requestIdentity = null; String requestSignature = null; String headerAuthorization = request.getHeader(HttpHeaders.AUTHORIZATION); if (headerAuthorization != null) { if (headerAuthorization.startsWith("AWS ")) { int colon = headerAuthorization.lastIndexOf(':', headerAuthorization.length() - 2); if (colon < 4) { throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT); } requestIdentity = headerAuthorization.substring(4, colon); requestSignature = headerAuthorization.substring(colon + 1); } else if (headerAuthorization.startsWith("AWS4-HMAC-SHA256 ")) { // Fail V4 signature requests to allow clients to retry with V2. throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT); } } else { requestIdentity = request.getParameter("AWSAccessKeyId"); requestSignature = request.getParameter("Signature"); } String[] path = uri.split("/", 3); for (int i = 0; i < path.length; i++) { path[i] = URLDecoder.decode(path[i], "UTF-8"); } Map.Entry<String, BlobStore> provider = blobStoreLocator.locateBlobStore(requestIdentity, path.length > 1 ? path[1] : null, path.length > 2 ? path[2] : null); if (requestIdentity != null) { if (provider == null) { throw new S3Exception(S3ErrorCode.INVALID_ACCESS_KEY_ID); } String expectedSignature = createAuthorizationSignature(request, uri, requestIdentity, provider.getKey()); if (!expectedSignature.equals(requestSignature)) { throw new S3Exception(S3ErrorCode.SIGNATURE_DOES_NOT_MATCH); } blobStore = provider.getValue(); String expiresString = request.getParameter("Expires"); if (expiresString != null) { long expires = Long.parseLong(expiresString); long nowSeconds = System.currentTimeMillis() / 1000; if (nowSeconds > expires) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED); } } } else { if (!anonymousIdentity) { throw new S3Exception(S3ErrorCode.ACCESS_DENIED); } else { blobStore = provider.getValue(); } } // emit NotImplemented for unknown parameters for (String parameter : Collections.list(request.getParameterNames())) { if (!SUPPORTED_PARAMETERS.contains(parameter)) { logger.error("Unknown parameters {} with URI {}", parameter, request.getRequestURI()); throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED); } } String uploadId = request.getParameter("uploadId"); switch (method) { case "DELETE": if (path.length <= 2 || path[2].isEmpty()) { handleContainerDelete(response, blobStore, path[1]); return; } else if (uploadId != null) { handleAbortMultipartUpload(request, response, blobStore, path[1], path[2], uploadId); return; } else { handleBlobRemove(response, blobStore, path[1], path[2]); return; } case "GET": if (uri.equals("/")) { handleContainerList(response, blobStore); return; } else if (path.length <= 2 || path[2].isEmpty()) { if ("".equals(request.getParameter("acl"))) { handleGetContainerAcl(response, blobStore, path[1]); return; } else if ("".equals(request.getParameter("location"))) { handleContainerLocation(response, blobStore, path[1]); return; } else if ("".equals(request.getParameter("uploads"))) { handleListMultipartUploads(response, blobStore, uploadId); return; } handleBlobList(request, response, blobStore, path[1]); return; } else { if ("".equals(request.getParameter("acl"))) { handleGetBlobAcl(response, blobStore, path[1], path[2]); return; } else if (uploadId != null) { handleListParts(request, response, blobStore, path[1], path[2], uploadId); return; } handleGetBlob(request, response, blobStore, path[1], path[2]); return; } case "HEAD": if (path.length <= 2 || path[2].isEmpty()) { handleContainerExists(response, blobStore, path[1]); return; } else { handleBlobMetadata(response, blobStore, path[1], path[2]); return; } case "POST": if ("".equals(request.getParameter("delete"))) { handleMultiBlobRemove(request, response, blobStore, path[1]); return; } else if ("".equals(request.getParameter("uploads"))) { handleInitiateMultipartUpload(request, response, blobStore, path[1], path[2]); return; } else if (uploadId != null) { handleCompleteMultipartUpload(request, response, blobStore, path[1], path[2], uploadId); return; } break; case "PUT": if (path.length <= 2 || path[2].isEmpty()) { if ("".equals(request.getParameter("acl"))) { handleSetContainerAcl(request, response, blobStore, path[1]); return; } handleContainerCreate(request, response, blobStore, path[1]); return; } else if (uploadId != null) { handleUploadPart(request, response, blobStore, path[1], path[2], uploadId); return; } else if (request.getHeader("x-amz-copy-source") != null) { handleCopyBlob(request, response, blobStore, path[1], path[2]); return; } else { if ("".equals(request.getParameter("acl"))) { handleSetBlobAcl(request, response, blobStore, path[1], path[2]); return; } handlePutBlob(request, response, blobStore, path[1], path[2]); return; } default: break; } logger.error("Unknown method {} with URI {}", method, request.getRequestURI()); throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED); }
From source file:io.brooklyn.ambari.server.AmbariServerImpl.java
@Override public void addServiceToCluster( @EffectorParam(name = "cluster", description = "Cluster name") final String cluster, @EffectorParam(name = "service", description = "Service name") final String service, @EffectorParam(name = "mappings", description = "Mappings of component to host") Map<String, String> mappings, @EffectorParam(name = "configuration", description = "Services Configuration", nullable = true, defaultValue = EffectorParam.MAGIC_STRING_MEANING_NULL) Map<String, Map<Object, Object>> configuration) { waitForServiceUp();/* w w w .j a va 2s. co m*/ final ServiceEndpoint serviceEndpoint = restAdapter.create(ServiceEndpoint.class); final HostEndpoint hostEndpoint = restAdapter.create(HostEndpoint.class); // Step 1 - Add the service to the cluster serviceEndpoint.addService(cluster, service); // Step 2 - Add Components to the service // Step 3 - Create host components for (Map.Entry<String, String> mapping : mappings.entrySet()) { serviceEndpoint.createComponent(cluster, service, mapping.getKey()); hostEndpoint.createHostComponent(cluster, mapping.getValue(), mapping.getKey()); } // Step 4 - Create configuration, if needed if (configuration != null) { for (Map.Entry<String, Map<Object, Object>> entry : configuration.entrySet()) { createServiceConfiguration(cluster, entry.getKey(), entry.getValue()); } } final Task installationTask = Tasks.builder().name(String.format("Install %s service", service)) .description( String.format("Install %s service on specified hosts through Ambari REST API", service)) .body(new Runnable() { @Override public void run() { // Step 5 - Install the service final Request request = serviceEndpoint.updateService(cluster, service, ImmutableMap .builder() .put("RequestInfo", ImmutableMap.builder() .put("context", String.format("Install %s service", service)).build()) .put("ServiceInfo", ImmutableMap.builder().put("state", "INSTALLED").build()) .build()); RequestCheckRunnable.check(request) .headers(ImmutableMap.of(HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(usernamePasswordCredentials))) .errorMessage(String.format( "Error during installation of service \"%s\". Please check the Ambari console for more details: %s", service, ambariUri)) .build().run(); } }).build(); final Task startTask = Tasks.builder().name(String.format("Start %s service", service)) .description(String.format("Start %s service on specified hosts through Ambari REST API", service)) .body(new Runnable() { @Override public void run() { // Step 6 - Start the service startService(cluster, service); } }).build(); // Queue the "Installation" subtask and wait for its completion. If something goes wrong during execution, an // exception will be thrown which will stop the effector and prevent the "start" subtask to run. DynamicTasks.queue(installationTask); // Queue the "Start" subtask. At this point, everything went fine. If something goes wrong during execution, an // exception will be thrown which will stop the effector. DynamicTasks.queue(startTask); }
From source file:io.brooklyn.ambari.server.AmbariServerImpl.java
@Override public void addHostsToHostGroup(final String blueprintName, final String hostgroupName, final List<String> hosts, final String cluster) { Iterable<Map> hostGroupMapping = Iterables.transform(hosts, fqdnsToMaps(blueprintName, hostgroupName)); LOG.info("hosts " + hostGroupMapping.iterator().hasNext()); HostEndpoint hostEndpoint = restAdapter.create(HostEndpoint.class); Request request = hostEndpoint.addHosts(cluster, Lists.newArrayList(hostGroupMapping)); RequestCheckRunnable.check(request)// ww w . j a v a 2s . c om .headers(ImmutableMap.of(HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(usernamePasswordCredentials))) .timeout(Duration.ONE_HOUR) .errorMessage(String.format("Error during adding %s to %s", hosts, hostgroupName)).build().run(); }
From source file:eu.seaclouds.policy.SeaCloudsManagementPolicy.java
private HttpToolResponse delete(String url, String mediaType, String username, String password) { URI apiEndpoint = URI.create(url); // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials if (username == null || password == null) { return HttpTool.httpDelete(HttpTool.httpClientBuilder().build(), apiEndpoint, MutableMap.of(HttpHeaders.CONTENT_TYPE, mediaType, HttpHeaders.ACCEPT, mediaType)); } else {//from w ww .ja v a 2s . com UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials return HttpTool.httpDelete( HttpTool.httpClientBuilder().uri(apiEndpoint).credentials(credentials).build(), apiEndpoint, MutableMap.of(HttpHeaders.CONTENT_TYPE, mediaType, HttpHeaders.ACCEPT, mediaType, HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(credentials))); } }
From source file:eu.seaclouds.policy.SeaCloudsManagementPolicy.java
private HttpToolResponse post(String url, String mediaType, String username, String password, byte[] payload) { URI apiEndpoint = URI.create(url); // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials if (username == null || password == null) { return HttpTool.httpPost(HttpTool.httpClientBuilder().build(), apiEndpoint, MutableMap.of(HttpHeaders.CONTENT_TYPE, mediaType, HttpHeaders.ACCEPT, mediaType), payload); } else {/*from w w w .j a v a 2 s .c om*/ UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials return HttpTool.httpPost(HttpTool.httpClientBuilder().uri(apiEndpoint).credentials(credentials).build(), apiEndpoint, MutableMap.of(HttpHeaders.CONTENT_TYPE, mediaType, HttpHeaders.ACCEPT, mediaType, HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(credentials)), payload); } }
From source file:io.brooklyn.ambari.server.AmbariServerImpl.java
@Override public void startService(@EffectorParam(name = "Cluster name") String cluster, @EffectorParam(name = "Service name") final String service) { waitForServiceUp();//from ww w . j a v a 2s .c om final Request request = restAdapter.create(ServiceEndpoint.class).updateService(cluster, service, ImmutableMap.builder() .put("RequestInfo", ImmutableMap.builder().put("context", String.format("Start %s service", service)) .build()) .put("ServiceInfo", ImmutableMap.builder().put("state", "STARTED").build()).build()); RequestCheckRunnable.check(request) .headers(ImmutableMap.of(HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(usernamePasswordCredentials))) .errorMessage(String.format( "Error during the start of service \"%s\". Please check the Ambari console for more details: %s", service, ambariUri)) .build().run(); }
From source file:io.brooklyn.ambari.server.AmbariServerImpl.java
private void connectAuthenticatedSensors() { hostsHttpFeed = HttpFeed.builder().entity(this).period(1000, TimeUnit.MILLISECONDS) .baseUri(String.format("%s/api/v1/hosts", ambariUri)) .credentials(usernamePasswordCredentials.getUserName(), usernamePasswordCredentials.getPassword()) .header(HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(usernamePasswordCredentials)) .poll(new HttpPollConfig<List<String>>(REGISTERED_HOSTS) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), getHosts())) .onFailureOrException(Functions.<List<String>>constant(ImmutableList.<String>of()))) .build();/* w ww .j a v a2s . c o m*/ clusterHttpFeed = HttpFeed.builder().entity(this).period(1000, TimeUnit.MILLISECONDS) .baseUri(String.format("%s/api/v1/clusters/%s/requests/%d", ambariUri, getConfig(AmbariCluster.CLUSTER_NAME), 1)) .credentials(usernamePasswordCredentials.getUserName(), usernamePasswordCredentials.getPassword()) .header(HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(usernamePasswordCredentials)) .poll(new HttpPollConfig<String>(CLUSTER_STATE) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), getRequestState())) .onFailureOrException(Functions.<String>constant(null))) .build(); }