Http basic auth with vert.x

I use the built-in httpclient to request a "get" to an external service that requires authentication. In particular, I am trying to send requests from my site. How to transfer user credentials in a request? I want to use basic auth instead of dealing with authentication tokens.

+5
source share
1 answer

Basic auth is the authorization header.

You should add this header with a value consisting of "base" (note the space) and your username: pass (separated by a colon), encoded in base64. It is safe if you use HTTPS.

Here is how I do it 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);

base64key, , - :

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

POST get, :

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

,

+15

All Articles