Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http basic auth with vert.x

Tags:

java

vert.x

I am using the built in httpclient to issue a "get" query to an external service that needs authentication. More specifically, I am trying to submit queries to splunk from my service. How do I pass in the user credentials in the request? I want to use the basic auth instead of dealing with authentication tokens.

like image 752
user2312682 Avatar asked Apr 23 '13 18:04

user2312682


People also ask

What is Vertx Web?

Vert. x Web Client is an asynchronous HTTP and HTTP/2 client. The Web Client makes easy to do HTTP request/response interactions with a web server, and provides advanced features like: Json body encoding / decoding. request/response pumping.

What is Handler in Vertx?

This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. @FunctionalInterface public interface Handler<E> A generic event handler. This interface is used heavily throughout Vert. x as a handler for all types of asynchronous occurrences.

What is router in Vertx?

public interface Router extends Handler<HttpServerRequest> A router receives request from an HttpServer and routes it to the first matching Route that it contains. A router can contain many routes. Routers are also used for routing failures.


1 Answers

Basic auth is all about the Authorization Header.

You should add that header with a value composed of "basic " (note the blank) and your login:pass (separated by a colon) encoded in base64. This is only secure if you're using HTTPS.

Here is how I get this done in vert.x :

HttpClient client = vertx.createHttpClient().setSSL(true)
    .setTrustAll(true) //You may not want to trust them all
    .setHost("api.myawesomeapi.com")
    .setPort(443);
HttpClientRequest clientRequest = client.get("/"+action+"/?"+params, new Handler<HttpClientResponse>() {
            public void handle(final HttpClientResponse response) {
                if (response.statusCode==200){
                    // It worked !
                } else {
                    // Oops
                }
            }
        });

clientRequest.putHeader(HttpHeaders.Names.AUTHORIZATION, "Basic "+base64key);

Here I already have the base64key, but if I had to create it, I would use something like :

base64key = Base64.encodeBytes(new StringBuilder(apiKey).append(":").append(secretKey).toString().getBytes(), Base64.DONT_BREAK_LINES);

If you use POST instead of get, don't forget to add the required headers :

clientRequest.putHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(params.getBytes().length))
        .putHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded")
        .write(params);

I hope it helps

Hugo

like image 160
HugoCrd Avatar answered Sep 28 '22 14:09

HugoCrd