Search in sources :

Example 6 with HttpSignatureSigner

use of com.disney.http.auth.client.signer.HttpSignatureSigner in project groovity by disney.

the class SampleClient method main.

public static void main(String[] args) throws Exception {
    try {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        // /// Ways to get the private key data (RSA):
        /*
         * Import KeyStore from file/url/etc.
         *   - assumes file has password but alias does not
         *   - must set loader password and type
         */
        Map<String, Object> config = new HashMap<String, Object>();
        config.put(KeyStoreValueHandler.KEYSTORE_PASSWORD, "filePassword");
        config.put(KeyStoreValueHandler.KEYSTORE_TYPE, "JCEKS");
        URIParcel<KeyStore> ks = new URIParcel<KeyStore>(KeyStore.class, new File("client_keystore.jceks").toURI(), config);
        KeyChain chain = new KeyStoreKeyChainImpl(ks, "passwordForPrivateKey".toCharArray());
        KeyChainKeyLoader loader = new KeyChainKeyLoader(chain);
        loader.setAlias("sample_webapp");
        /*
         * Import PrivateKey from PKCS8 pem file
         *   - assumes no password protection or encryption
         */
        // ExternalKeyLoader keyLoader = new ExternalKeyLoader("/client_key.pem", localContext);
        // keyLoader.setAlgorithm("RSA");
        URIParcel<PrivateKey> keyLoader = new URIParcel<PrivateKey>(PrivateKey.class, new java.net.URI("file:client_key.pem"));
        /*
         * Create own key and to set that in the signer. Can write key to file as desired
         *
         * Here, generate a KeyPair
         *   - only RSA
         *   - can set bit size to 1024 or 2048
         *   - must save the public key for verification use
         */
        KeyPair pair = KeyUtils.generateKeyPair(2048);
        // // Write privateKey to a file (PKCS8, uses base64encoding)
        // KeyUtils.writePrivateKeyToFile(pair,"/Users/kobar004/misc/auth-backup/newKey-priv.pem");
        KeyObjectKeyLoader privateKeyLoader = new KeyObjectKeyLoader(pair.getPrivate());
        // // write public KeyStore to file.
        // String publicKeyStoreLocation = "/Users/kobar004/misc/auth-backup/newKey-pub.store";
        // KeyUtils.writePublicKeyStoreToFile(pair.getPublic(), publicKeyStoreLocation, "RSA", "rachel");
        // Ways to set the symmetric key data (HMAC):
        /*
         * Set Key value explicitly
         */
        KeyObjectKeyLoader simpleLoader = new KeyObjectKeyLoader("hmac-sha256", "someBase64Secret");
        /*
         * Configuring the HttpSignatureSigner (HttpRequestInterceptor)
         *
         *   - must set the keyId / alias
         *   - must set key/encryption/algorithm
         *   - if no headers are set, default to just using the Date header
         *   - Lastly, the signer must be added to the clientBuilder
         */
        // /// Signing for SIGNATURE Authorization with imported RSA key
        // setting the key of the singer either with a loader or a key.
        HttpSignatureSigner signer = new HttpSignatureSigner();
        signer.setKeyId("apiUser123");
        signer.setHeaders(Arrays.asList("(request-target)", "host", "x-date"));
        // set key (choose one)
        // signer.setKey(loader);
        // signer.setKey(keyLoader);
        signer.setKeyLoader(simpleLoader);
        clientBuilder.addInterceptorLast(signer);
        // ///
        CloseableHttpClient client = clientBuilder.build();
        getRequest(client, "http://localhost:8080/");
        client.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HashMap(java.util.HashMap) URIParcel(com.disney.uriparcel.URIParcel) KeyChain(com.disney.http.auth.keychain.KeyChain) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) KeyStoreKeyChainImpl(com.disney.http.auth.keychain.KeyStoreKeyChainImpl) KeyChainKeyLoader(com.disney.http.auth.client.keyloader.KeyChainKeyLoader) HttpSignatureSigner(com.disney.http.auth.client.signer.HttpSignatureSigner) KeyObjectKeyLoader(com.disney.http.auth.client.keyloader.KeyObjectKeyLoader) File(java.io.File)

Example 7 with HttpSignatureSigner

use of com.disney.http.auth.client.signer.HttpSignatureSigner in project groovity by disney.

the class Http method tag.

@SuppressWarnings({ "rawtypes", "unchecked" })
public Object tag(Map attributes, Closure body) throws Exception {
    Object url = resolve(attributes, "url");
    if (url == null) {
        throw new RuntimeException("<g:http> requires 'url' attribute");
    }
    Object var = resolve(attributes, VAR);
    String method = "GET";
    Object methodAtt = resolve(attributes, "method");
    if (methodAtt != null) {
        method = methodAtt.toString();
    }
    boolean followRedirects = true;
    Object redirectsAtt = resolve(attributes, "redirects");
    if (redirectsAtt != null) {
        followRedirects = Boolean.parseBoolean(redirectsAtt.toString());
    }
    CookieOption cookieOption = CookieOption.DEFAULT;
    Object cookiesAtt = resolve(attributes, "cookies");
    if (cookiesAtt != null) {
        cookieOption = CookieOption.valueOf(cookiesAtt.toString().toUpperCase());
    }
    Object timeout = resolve(attributes, TIMEOUT);
    final int timeoutSeconds = timeout == null ? -1 : timeout instanceof Number ? ((Number) timeout).intValue() : Integer.parseInt(timeout.toString());
    Object target = resolve(attributes, "to");
    if (target instanceof Class) {
        if (!Object.class.equals(target)) {
            target = ((Class) target).newInstance();
        }
    }
    if (target == null) {
        target = Object.class;
    }
    Object async = resolve(attributes, "async");
    if (async != null && !(async instanceof Boolean)) {
        async = Boolean.valueOf(async.toString());
    }
    HttpEntity dataEntity = null;
    Object data = resolve(attributes, "data");
    HttpClientContext clientContext = resolve(attributes, "context", HttpClientContext.class);
    if (clientContext == null) {
        clientContext = HttpClientContext.create();
    }
    if (clientContext.getCookieStore() == null) {
        // we don't want to let cookies be shared across contexts
        clientContext.setCookieStore(new BasicCookieStore());
    }
    if (clientContext.getAuthCache() == null) {
        // we also don't want to share credentials across contexts
        clientContext.setAuthCache(new BasicAuthCache());
    }
    final HttpClientContext fContext = clientContext;
    ScriptHelper context = getScriptHelper(body);
    Object oldOut = get(context, OUT);
    // execute body to assemble URL params, headers, post body
    Map variables = context.getBinding().getVariables();
    URI uri;
    URIBuilder builder;
    ArrayList<Header> headers;
    Optional<UserPass> userPass;
    Optional<HttpSignatureSigner> signer;
    Optional<HttpRequestInterceptor> interceptor;
    try {
        builder = new URIBuilder(url.toString());
        bind(context, Uri.CURRENT_URI_BUILDER, builder);
        headers = new ArrayList<Header>();
        bind(context, com.disney.groovity.tags.Header.CURRENT_LIST_FOR_HEADERS, headers);
        Credentials.acceptCredentials(variables);
        Signature.acceptSigner(variables);
        acceptInterceptor(variables);
        StringWriter sw = new StringWriter();
        bind(context, OUT, sw);
        try {
            Object rval = body.call();
            if (rval instanceof Writable) {
                ((Writable) rval).writeTo(sw);
            }
        } finally {
            bind(context, OUT, oldOut);
            userPass = Credentials.resolveCredentials(variables);
            signer = Signature.resolveSigner(variables);
            interceptor = resolveInterceptor(variables);
        }
        String val = sw.toString();
        if (val.trim().length() > 0) {
            dataEntity = new StringEntity(val);
        }
        uri = builder.build();
        if (userPass.isPresent()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(userPass.get().getUser(), new String(userPass.get().getPass())));
            clientContext.setCredentialsProvider(credsProvider);
        }
    } catch (URISyntaxException e1) {
        throw new RuntimeException("Invalid URI " + url, e1);
    } finally {
        unbind(context, Uri.CURRENT_URI_BUILDER);
        unbind(context, com.disney.groovity.tags.Header.CURRENT_LIST_FOR_HEADERS);
    }
    final HttpRequestBase request = "POST".equalsIgnoreCase(method) ? new HttpPost(uri) : "PUT".equalsIgnoreCase(method) ? new HttpPut(uri) : "HEAD".equalsIgnoreCase(method) ? new HttpHead(uri) : "DELETE".equalsIgnoreCase(method) ? new HttpDelete(uri) : "OPTIONS".equalsIgnoreCase(method) ? new HttpOptions(uri) : new HttpGet(uri);
    if (headers.size() > 0) {
        request.setHeaders(headers.toArray(new Header[0]));
    }
    if (request instanceof HttpEntityEnclosingRequest) {
        if (data != null) {
            // decide on strategy to convert data to entity
            if (data instanceof HttpEntity) {
                dataEntity = (HttpEntity) data;
            } else {
                // look at content type for a hint
                Header targetType = request.getFirstHeader("Content-Type");
                if (targetType != null && targetType.getValue().contains("json")) {
                    CharArrayWriter caw = new CharArrayWriter();
                    new ModelJsonWriter(caw).visit(data);
                    dataEntity = new StringEntity(caw.toString());
                } else if (targetType != null && targetType.getValue().contains("xml")) {
                    if (data instanceof groovy.util.Node) {
                        dataEntity = new StringEntity(XmlUtil.serialize((groovy.util.Node) data));
                    } else if (data instanceof GPathResult) {
                        dataEntity = new StringEntity(XmlUtil.serialize((GPathResult) data));
                    } else if (data instanceof Element) {
                        dataEntity = new StringEntity(XmlUtil.serialize((Element) data));
                    } else if (data instanceof Document) {
                        dataEntity = new StringEntity(XmlUtil.serialize(((Document) data).getDocumentElement()));
                    } else {
                        // if it's not an XML model assume it's a well formed XML string
                        dataEntity = new StringEntity(data.toString());
                    }
                } else if ((targetType != null && targetType.getValue().contains("x-www-form-urlencoded")) || (targetType == null && (data instanceof Map || data instanceof List))) {
                    // key/value pairs, accept a map, a list of maps, or a list of NameValuePairs
                    Iterator source = data instanceof Map ? ((Map) data).entrySet().iterator() : ((List) data).iterator();
                    ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
                    while (source.hasNext()) {
                        Object next = source.next();
                        if (next instanceof Map.Entry) {
                            Map.Entry entry = (Entry) next;
                            pairs.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue() != null ? entry.getValue().toString() : ""));
                        } else if (next instanceof NameValuePair) {
                            pairs.add((NameValuePair) next);
                        } else if (next instanceof Map) {
                            Iterator<Map.Entry> sub = ((Map) next).entrySet().iterator();
                            while (sub.hasNext()) {
                                Map.Entry se = sub.next();
                                pairs.add(new BasicNameValuePair(se.getKey().toString(), se.getValue() != null ? se.getValue().toString() : ""));
                            }
                        }
                    }
                    dataEntity = new UrlEncodedFormEntity(pairs);
                } else if (targetType != null && targetType.getValue().contains("multipart/form-data")) {
                    // list of maps, each map must contain "name" and "body", plus optional "type" and "filename"
                    Iterator<Map> parts = ((List<Map>) data).iterator();
                    MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
                    while (parts.hasNext()) {
                        Map part = parts.next();
                        Object pbody = part.get("body");
                        String name = (String) part.get("name");
                        String type = (String) part.get("type");
                        String filename = (String) part.get("filename");
                        ContentType ct = type != null ? ContentType.parse(type) : null;
                        if (pbody instanceof File) {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_BINARY;
                            }
                            meBuilder.addBinaryBody(name, (File) pbody, ct, filename);
                        } else if (pbody instanceof byte[]) {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_BINARY;
                            }
                            meBuilder.addBinaryBody(name, (byte[]) pbody, ct, filename);
                        } else if (pbody instanceof ContentBody) {
                            meBuilder.addPart(name, (ContentBody) pbody);
                        } else if (pbody instanceof InputStream) {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_BINARY;
                            }
                            meBuilder.addBinaryBody(name, (InputStream) pbody, ct, filename);
                        } else {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_TEXT;
                            }
                            meBuilder.addTextBody(name, pbody.toString(), ct);
                        }
                    }
                    dataEntity = meBuilder.build();
                } else {
                    // no help from content type header, check for modeled XML
                    if (data instanceof groovy.util.Node) {
                        dataEntity = new StringEntity(XmlUtil.serialize((groovy.util.Node) data), ContentType.APPLICATION_XML);
                    } else if (data instanceof GPathResult) {
                        dataEntity = new StringEntity(XmlUtil.serialize((GPathResult) data), ContentType.APPLICATION_XML);
                    } else if (data instanceof Element) {
                        dataEntity = new StringEntity(XmlUtil.serialize((Element) data), ContentType.APPLICATION_XML);
                    } else if (data instanceof Document) {
                        dataEntity = new StringEntity(XmlUtil.serialize(((Document) data).getDocumentElement()), ContentType.APPLICATION_XML);
                    } else if (data instanceof byte[]) {
                        dataEntity = new ByteArrayEntity((byte[]) data);
                    } else if (data instanceof InputStream) {
                        dataEntity = new InputStreamEntity((InputStream) data);
                    } else if (data instanceof File) {
                        dataEntity = new FileEntity((File) data);
                    } else {
                        // best option left is to post the toString value of the data
                        dataEntity = new StringEntity(data.toString());
                    }
                }
            }
        }
        if (dataEntity != null) {
            ((HttpEntityEnclosingRequest) request).setEntity(dataEntity);
        }
    }
    RequestConfig.Builder configBuilder = request.getConfig() == null ? RequestConfig.custom() : RequestConfig.copy(request.getConfig());
    if (!followRedirects) {
        configBuilder.setRedirectsEnabled(followRedirects);
    }
    configBuilder.setCookieSpec(cookieOption.getCookieSpec());
    request.setConfig(configBuilder.build());
    final String varName = var != null ? var.toString() : null;
    ResponseHandler handler = null;
    try {
        Function handlerFunction = (Function) get(body, Handler.HANDLER_BINDING);
        if (handlerFunction != null) {
            handler = new ResponseHandler<Object>() {

                @Override
                public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                    return handlerFunction.apply(response);
                }
            };
        }
        unbind(body, Handler.HANDLER_BINDING);
    } catch (Exception e) {
    }
    if (handler == null) {
        handler = new AutoParsingResponseHandler(target);
    }
    final List<HttpRequestInterceptor> interceptors = new ArrayList<>();
    if (signer.isPresent()) {
        interceptors.add(signer.get());
    }
    if (interceptor.isPresent()) {
        interceptors.add(interceptor.get());
    }
    final ResponseHandler rHandler = handler;
    final boolean isAsync = (async != null && Boolean.TRUE.equals(async));
    Callable<Object> requester = new Callable() {

        public Object call() throws Exception {
            TimeoutTask timeoutTask = null;
            if (timeoutSeconds > 0) {
                timeoutTask = new TimeoutTask(request);
                timeoutTimer.schedule(timeoutTask, timeoutSeconds * 1000);
            }
            try {
                Binding oldThreadBinding = null;
                if (isAsync) {
                    oldThreadBinding = ScriptHelper.THREAD_BINDING.get();
                    Binding asyncBinding = new Binding();
                    asyncBinding.setVariable("request", request);
                    ScriptHelper.THREAD_BINDING.set(asyncBinding);
                }
                try {
                    for (HttpRequestInterceptor interceptor : interceptors) {
                        interceptor.process(request, null);
                    }
                    return httpClient.execute(request, rHandler, fContext);
                } finally {
                    if (isAsync) {
                        if (oldThreadBinding == null) {
                            ScriptHelper.THREAD_BINDING.remove();
                        } else {
                            ScriptHelper.THREAD_BINDING.set(oldThreadBinding);
                        }
                    }
                }
            } catch (HttpResponseException e) {
                if (isAsync) {
                    log.error("Async HTTP response error for " + request.getURI() + ": " + e.getMessage());
                }
                throw e;
            } catch (Exception e) {
                if (request.isAborted()) {
                    if (isAsync) {
                        log.error("Async <g:http> request timed out for " + request.getURI());
                    }
                    throw new TimeoutException("Timed out executing <g:http> for " + request.getURI());
                } else {
                    if (isAsync) {
                        log.error("Async <g:http> request error for " + request.getURI(), e);
                    }
                    throw new RuntimeException("Error executing <g:http> for " + request.getURI(), e);
                }
            } finally {
                if (timeoutTask != null) {
                    timeoutTask.cancel();
                }
            }
        }
    };
    Object responseVar = null;
    if (isAsync) {
        // return the Future to the calling code
        Future<Object> f = asyncExecutor.submit(requester);
        responseVar = new Future<Object>() {

            @Override
            public boolean cancel(boolean mayInterruptIfRunning) {
                return f.cancel(mayInterruptIfRunning);
            }

            @Override
            public boolean isCancelled() {
                return f.isCancelled();
            }

            @Override
            public boolean isDone() {
                return f.isDone();
            }

            @Override
            public Object get() throws InterruptedException, ExecutionException {
                GroovityStatistics.startExecution("http(async)");
                try {
                    return f.get();
                } finally {
                    GroovityStatistics.endExecution();
                }
            }

            @Override
            public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                GroovityStatistics.startExecution("http(async)");
                try {
                    return f.get(timeout, unit);
                } finally {
                    GroovityStatistics.endExecution();
                }
            }
        };
    } else {
        // return the parsed/handled response object
        GroovityStatistics.startExecution("http(sync)");
        try {
            responseVar = requester.call();
        } finally {
            GroovityStatistics.endExecution();
        }
    }
    if (varName != null) {
        bind(context, varName, responseVar);
    }
    return responseVar;
}
Also used : Entry(java.util.Map.Entry) HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) ContentType(org.apache.http.entity.ContentType) ResponseHandler(org.apache.http.client.ResponseHandler) HttpOptions(org.apache.http.client.methods.HttpOptions) ArrayList(java.util.ArrayList) Writable(groovy.lang.Writable) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) Document(org.w3c.dom.Document) HttpPut(org.apache.http.client.methods.HttpPut) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ArrayList(java.util.ArrayList) TimeoutException(java.util.concurrent.TimeoutException) Binding(groovy.lang.Binding) RequestConfig(org.apache.http.client.config.RequestConfig) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) ContentBody(org.apache.http.entity.mime.content.ContentBody) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) AuthScope(org.apache.http.auth.AuthScope) ModelJsonWriter(com.disney.groovity.model.ModelJsonWriter) ScriptHelper(com.disney.groovity.util.ScriptHelper) Map(java.util.Map) File(java.io.File) HttpEntity(org.apache.http.HttpEntity) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpGet(org.apache.http.client.methods.HttpGet) Element(org.w3c.dom.Element) HttpResponseException(org.apache.http.client.HttpResponseException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) HttpHead(org.apache.http.client.methods.HttpHead) CharArrayWriter(java.io.CharArrayWriter) Callable(java.util.concurrent.Callable) Function(java.util.function.Function) Entry(java.util.Map.Entry) StringWriter(java.io.StringWriter) HttpSignatureSigner(com.disney.http.auth.client.signer.HttpSignatureSigner) Iterator(java.util.Iterator) GPathResult(groovy.util.slurpersupport.GPathResult) ExecutionException(java.util.concurrent.ExecutionException) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) FileEntity(org.apache.http.entity.FileEntity) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) UserPass(com.disney.groovity.tags.Credentials.UserPass) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Example 8 with HttpSignatureSigner

use of com.disney.http.auth.client.signer.HttpSignatureSigner in project groovity by disney.

the class Signature method tag.

@SuppressWarnings({ "rawtypes", "unchecked" })
public Object tag(Map attributes, Closure body) throws Exception {
    Object keyId = resolve(attributes, "keyId");
    if (keyId == null) {
        throw new RuntimeException("<g:signature> requires a keyId for signing");
    }
    Callable<Key> useLoader = null;
    Object key = resolve(attributes, "key");
    if (key == null) {
        Object keystore = resolve(attributes, "keystore");
        if (keystore == null) {
            throw new RuntimeException("<g:signature> requires a key or keystore for signing");
        }
        String password = resolve(attributes, "password", String.class);
        if (password == null) {
            throw new RuntimeException("<g:signature> requires a password when using a keystore");
        }
        String alias = resolve(attributes, "alias", String.class);
        if (alias == null) {
            throw new RuntimeException("<g:signature> requires an alias when using a keystore");
        }
        if (!(keystore instanceof KeyStore)) {
            String ksl = keystore.toString();
            KeyChainKeyLoader loader = keystores.get(ksl);
            if (loader == null) {
                URIParcel<KeyStore> keystoreParcel = new URIParcel<KeyStore>(KeyStore.class, new URI(ksl));
                keystoreParcel.setRefresh(60000);
                Map conf = new HashMap();
                conf.put("password", password);
                String type = resolve(attributes, "type", String.class);
                if (type != null) {
                    conf.put("type", type);
                }
                keystoreParcel.setConfig(conf);
                loader = new KeyChainKeyLoader(new KeyStoreKeyChainImpl(keystoreParcel, password.toCharArray()), alias);
                keystores.put(ksl, loader);
            }
            useLoader = loader;
        } else {
            useLoader = new KeyChainKeyLoader(new KeyStoreKeyChainImpl((KeyStore) keystore, password.toCharArray()), alias);
        }
    }
    if (key instanceof Callable<?>) {
        useLoader = (Callable<Key>) key;
    } else if (key instanceof Key) {
        useLoader = new KeyObjectKeyLoader((Key) key);
    }
    String useAlgorithm = "hmac-sha256";
    Object algorithm = resolve(attributes, "algorithm");
    if (algorithm != null) {
        useAlgorithm = algorithm.toString();
    }
    if (useLoader == null) {
        if (useAlgorithm.startsWith("rsa")) {
        // TODO load private key from object
        } else {
            String signingAlg = Algorithms.getSecurityAlgorithm(useAlgorithm);
            // System.out.println("Generating hmac key "+signingAlg+" with "+new String(DatatypeConverter.parseBase64Binary(key.toString())));
            useLoader = new KeyObjectKeyLoader(new SecretKeySpec(DatatypeConverter.parseBase64Binary(key.toString()), signingAlg));
        }
    }
    Object headers = resolve(attributes, "headers");
    HttpSignatureSigner signer = new HttpSignatureSigner();
    signer.setAlgorithm(useAlgorithm);
    signer.setKeyId(keyId.toString());
    signer.setKeyLoader(useLoader);
    if (headers != null) {
        if (!(headers instanceof List)) {
            throw new RuntimeException("signature tag requires that 'headers' attribut contains a List, instead found " + headers.getClass().toString());
        }
        signer.setHeaders((List) headers);
    }
    bind(body, SIGNATURE_BINDING, Optional.of(signer));
    return null;
}
Also used : URIParcel(com.disney.uriparcel.URIParcel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) KeyStore(java.security.KeyStore) URI(java.net.URI) Callable(java.util.concurrent.Callable) KeyStoreKeyChainImpl(com.disney.http.auth.keychain.KeyStoreKeyChainImpl) SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeyChainKeyLoader(com.disney.http.auth.client.keyloader.KeyChainKeyLoader) HttpSignatureSigner(com.disney.http.auth.client.signer.HttpSignatureSigner) List(java.util.List) KeyObjectKeyLoader(com.disney.http.auth.client.keyloader.KeyObjectKeyLoader) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Map(java.util.Map) Key(java.security.Key)

Aggregations

HttpSignatureSigner (com.disney.http.auth.client.signer.HttpSignatureSigner)8 KeyObjectKeyLoader (com.disney.http.auth.client.keyloader.KeyObjectKeyLoader)5 HttpGet (org.apache.http.client.methods.HttpGet)5 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)4 Test (org.junit.Test)4 KeyChainKeyLoader (com.disney.http.auth.client.keyloader.KeyChainKeyLoader)3 KeyStoreKeyChainImpl (com.disney.http.auth.keychain.KeyStoreKeyChainImpl)3 URIParcel (com.disney.uriparcel.URIParcel)3 File (java.io.File)3 URI (java.net.URI)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 UserPass (com.disney.groovity.tags.Credentials.UserPass)2 ScriptHelper (com.disney.groovity.util.ScriptHelper)2 SignatureAuthorization (com.disney.http.auth.SignatureAuthorization)2 ClientAuthorizationRequest (com.disney.http.auth.client.ClientAuthorizationRequest)2 KeyChain (com.disney.http.auth.keychain.KeyChain)2 Writable (groovy.lang.Writable)2 IOException (java.io.IOException)2 StringWriter (java.io.StringWriter)2