Jordan Macey-Smith
Jordan Macey-Smith

Reputation: 321

Unable to authorize in API Basic Authentication in Java

I'm attempting to authorize with the Lithium Social Web API in Java. I am relatively new to Java but it feels like what I have should work. I am using webTarget and Invocation builder to try and pass the authorization through the header but continually get an unauthorized response.

I've changed the authentication to Base64 encoded via the AuthenticationClass below and can authenticate through hurl.it with the API and can get data back so the user credentials are correct. I've attached a sample of the code with the username and password removed. If anyone has any ideas i would appreciate it.

this.webTarget = this.client.target("https://socialweb-analytics.lcloud.com");

    WebTarget webTargetSessionAuthenticate = webTarget.path("/api/public/reports/report/conversation");

    AuthenticationClass newAuth = new AuthenticationClass();
    newAuth.loginValue("USERNAME", "PASSWORD");
    loginValue = newAuth.encodeLogin();

    Object [] starttimeParamObjects = {new String("1438351200000")};
    Object [] reportformatParamObjects = {new String("csv")};
    Object [] endtimeParamObjects = {new String("1439128800000")};
    Object [] companykeyParamObjects = {new String("XXX")};

    System.out.println(loginValue);

     WebTarget webTargetSessionAuthenticateWithQueryParams = webTargetSessionAuthenticate
             .queryParam("startTime", starttimeParamObjects)
             .queryParam("endTime", endtimeParamObjects)
             .queryParam("reportFormat", reportformatParamObjects)
             .queryParam("companyKey", companykeyParamObjects);     

     System.out.println(webTargetSessionAuthenticateWithQueryParams);

     Invocation.Builder invocationBuilderAuth =
                webTargetSessionAuthenticateWithQueryParams.request();
     invocationBuilderAuth.header(HttpHeaders.AUTHORIZATION, "Basic " + loginValue);


     Response response = invocationBuilderAuth.get();//Entity.entity("", MediaType.TEXT_PLAIN_TYPE));
     int responseStatus = response.getStatus();
     System.out.println(responseStatus);

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

Upvotes: 1

Views: 225

Answers (2)

djangofan
djangofan

Reputation: 29689

Out of the box, the HttpClient doesn’t do preemptive authentication. If you get totally stuck you can try a variation on Basic auth called "preemptive auth" using AuthCache and BasicScheme (not used with a default basic auth).

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68725

A space is required between your header string "Basic" and "encoded login Value value". So try to change this

 invocationBuilderAuth.header(HttpHeaders.AUTHORIZATION, "Basic" + loginValue);

to

 invocationBuilderAuth.header(HttpHeaders.AUTHORIZATION, "Basic " + loginValue);

Upvotes: 1

Related Questions