1

I need to get access from java application to some RESTful web service which uses token-based authentication. As I understood the best choice for this purpose is to use JAX-RS-based libraries like Jersey, but I am very new to this matter. Maybe someone could help me by giving example code of proper request to get a token from web service.

What we have:

  • URI of the token issuing server. It uses oAuth2 authorization.
  • clientId and clientSecret. We have to submit them to the token issuing server which will verify them and return a token.
  • URI of the web service itself.
  • username and password for service access.

As I understood, to get a token I have to send POST request along with the following headers:

  • "Authorization", "Basic YWRhMGI3NTicdscsN2I0MjNjM2EwNWQ0MjM2ZTg6QU1hS0ltUEZJaUFSR3dGMmJ3NjZZVi9Ec05YZTd0ZkEerfrvegezNoND0=" ("Basic " + base64 encoded "clientId:clientSecret")
  • "Accept", "application/x-www-form-urlencoded"
  • "Content-Type", "application/json;odata=verbose"

and the following parameter:

grant_type=password&username=someusername&password=somepassword&scope=profile

Hope somebody will help me with example code.

Daulet Kshibekov
  • 181
  • 2
  • 2
  • 8

2 Answers2

4

Resolved!

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public void getHttpCon() throws Exception{

    String POST_PARAMS = "grant_type=password&username=someusrname&password=somepswd&scope=profile";
    URL obj = new URL("http://someIP/oauth/token");
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json;odata=verbose");
    con.setRequestProperty("Authorization",
            "Basic Base64_encoded_clientId:clientSecret");
    con.setRequestProperty("Accept",
            "application/x-www-form-urlencoded");

    // For POST only - START
    con.setDoOutput(true);
    OutputStream os = con.getOutputStream();
    os.write(POST_PARAMS.getBytes());
    os.flush();
    os.close();
    // For POST only - END

    int responseCode = con.getResponseCode();
    System.out.println("POST Response Code :: " + responseCode);

    if (responseCode == HttpURLConnection.HTTP_OK) { //success
        BufferedReader in = new BufferedReader(new InputStreamReader(
                con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        System.out.println(response.toString());
    } else {
        System.out.println("POST request not worked");
    }
}    
Daulet Kshibekov
  • 181
  • 2
  • 2
  • 8
0

Some points:

  • URL request you specify is the one belonging to Resource Owner Password Credentials Grant. Be sure you are under the scenario this grant is meant for (more details here).
  • JAX-RS is about implementing the REST apis, not about the client-side calls (maybe you were talking about "jax-rs client"? if that's the case, in terms of oauth, it falls into my last point category as any other http client).
  • There are libraries that can handle obtaining access token for you, so that you only need to provide properties and decide what to do with the resulting token. For example, if you are ok using spring, Spring Security OAuth2 (talking about the "client role" configuration only; you will be using external authorization server).
  • If those libraries do not fit your case: You only need to implement/use an http client to do standard calls to that authorization server (they are just REST apis). Some options: apache httpcomponents, Spring RestTemplate, jdk HttpUrlConnection
Community
  • 1
  • 1
albert_nil
  • 1,648
  • 7
  • 9
  • There is also a [JAX-RX Client API](https://docs.oracle.com/javaee/7/tutorial/jaxrs-client.htm) (mainly intended for, but not limited to REST) which may have added some confusion. – toKrause Aug 15 '17 at 08:29
  • you are right thnx, will edit answer to avoid confusion (in any case OP talked about jersey which is related with the service implementation, not with the client afaik). IMHO jax-rs client is an awful name, taking into consideration that the documentation itself states that the client is not for jaxrs services, but instead for any REST service :p – albert_nil Aug 15 '17 at 08:50
  • It gets even worse, because Jersey, as a JAX-RS implementation, also implements the JAX-RS Client API in a component named `jersey-client`. – toKrause Aug 15 '17 at 08:53
  • hahaah okok, removed "jersey not being client" comment at all – albert_nil Aug 15 '17 at 08:59