Adding authorization header to Jersey SSE Client request

Quick picture Quick · Mar 15, 2015 · Viewed 51.2k times · Source

I am using Jersey client to connect to an SSE stream. The server requires that I add a header to the http request for authorization, but I can't figure out how to add the header.

Here is my code:

Client client = ClientBuilder.newBuilder().register(SseFeature.class).build();
WebTarget target = client.target(baseurl + "/v1/devices/events/");
eventSource = EventSource.target(target).build();
eventSource.register(getEventListener());
eventSource.open();

Here is an example of the header I need to add:

Authorization: Bearer 38bb7b318cc6898c80317decb34525844bc9db55

Answer

lrnzcig picture lrnzcig · Mar 15, 2015

It would be something like this for Basic Authentication:

Client client = ClientBuilder.newClient();
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder().build();
client.register(feature);
client.register(SseFeature.class);
WebTarget target = client.target(baseurl + "/v1/devices/events/")
    .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_USERNAME, "...")
    .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_PASSWORD, "...");

...

You already get the password encoded by Jersey.

And if it is a token:

Client client = ClientBuilder.newClient();
WebTarget target = client.target(baseurl + "/v1/devices/events/")
    .request("...")     
    .header(HttpHeaders.AUTHORIZATION, "Bearer " + "... encoded token ...");

Hope it helps!