Jersey Client API - authentication

At first I got this working as documented in the Jersey User guide

Authenticator.setDefault (authinstance);

However I did not like this as it relied on setting a global authenticator. After some research I discovered that Jersey has a HTTPBasicAuthFilter which is even easier to use.

Client c = Client.create();
c.addFilter(new HTTPBasicAuthFilter(user, password));

See: https://jersey.github.io/nonav/apidocs/1.10/jersey/com/sun/jersey/api/client/filter/HTTPBasicAuthFilter.html https://jersey.github.io/nonav/apidocs/1.10/jersey/com/sun/jersey/api/client/filter/Filterable.html#addFilter(com.sun.jersey.api.client.filter.ClientFilter)


Jersey 2.x:

HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder()
    .nonPreemptive()
    .credentials("user", "password")
    .build();

ClientConfig clientConfig = new ClientConfig();
clientConfig.register(feature) ;

Client client = ClientBuilder.newClient(clientConfig);

Reference: 5.9.1. Http Authentication Support


There's a small section in the Jersey User guide about Client authentication. I'd recommend you follow its advice and try using Apache HTTP Client instead of HttpURLConnection, as it has much better support for just about anything you'd want to do.


Adding this answer as I keep finding answers for older versions of Jersey that are no longer relevant in 2.x.

For Jersey 2 there are several ways. Take a look at:

JavaDoc for org.glassfish.jersey.client.authentication.HttpAuthenticationFeature

Here is the one that is working for me (simplest basic auth IMHO).

    ClientConfig config = new ClientConfig();

    HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("username", "password");

    Client client = ClientBuilder.newClient(config);
    client.register(feature);

    WebTarget webTarget = client.target("http://api.asite.com/api").path("v1/reports/list");
    Invocation.Builder invocationBuilder =  webTarget.request(MediaType.TEXT_PLAIN_TYPE);

    Response response = invocationBuilder.get();

    System.out.println( response.getStatus() );
    System.out.println( response.readEntity(String.class) );

If you are testing a Dropwizard application (maybe it suits any REST service), you can use this as an example: https://github.com/dropwizard/dropwizard/blob/v0.8.1/dropwizard-auth/src/test/java/io/dropwizard/auth/basic/BasicAuthProviderTest.java