OAuth 2.0 service invocation

A registered OAuth client can invoke the WebSphere® Application Server OAuth service authorization endpoint to request an access token. A registered OAuth client can also invoke the WebSphere Application Server OAuth service token endpoint to request an access token. The client then can use the access token to request protected web resources from WebSphere Application Server.

WebSphere Application Server OAuth 2.0 service supports the following flows.

Authorization code flow

Invoke authorization endpoint to request authorization code.
The OAuth client redirects the resource owner or user to the WebSphere Application Server OAuth 2.0 Authorization Service by adding its client id, client secret, state, redirect URI, and the optional scopes.
https://host_name:port_number/oauth2/endpoint/provider_name/authorize
or
https://host_name:port_number/oauth2/declarativeEndpoint/provider_name/authorize
Invoke OAuth token endpoint to request access token.
The OAuth client requests an access token from the WebSphere Application Server OAuth 2.0 token endpoint by adding authorization_code grant type, authorization code, redirect_url, and client_id as request parameters.
https://host_name:port_number/oauth2/endpoint/provider_name/token
The following example shows the constructions of the URIs when using authorization code, and the use of the access token to access web resources:
String charset = "UTF-8";
String param1 = "code";

if (isAuthorizationCode){
  String query = String.format("response_type=%s&
                               client_id=%s&
                               client_secret=%s&
                               state=%s&
                               redirect_uri=%s&
                               scope=%s",
                               URLEncoder.encode(param1, charset),
                               URLEncoder.encode(clientId, charset),
                               URLEncoder.encode(clientSecret, charset),
                               URLEncoder.encode(state, charset),
                               URLEncoder.encode(redirectURI, charset),
                               URLEncoder.encode(scope, charset));
  String s = authorizationEndPoint + "?" + query;
  System.out.println("Visit: " + s + "\nand grant permission");
  System.out.print("Now enter the OAuth code you have received in redirect uri :");
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String code = br.readLine();
  param1 = "authorization_code";
  query = String.format("grant_type=%s&
                        code=%s&
                        client_id=%s&
                        client_secret=%s&
                        state=%s&
                        redirect_uri=%s&
                        scope=%s",
                        URLEncoder.encode(param1, charset),
                        URLEncoder.encode(code, charset),
                        URLEncoder.encode(clientId, charset),
                        URLEncoder.encode(clientSecret, charset),
                        URLEncoder.encode(state, charset),
                        URLEncoder.encode(redirectURI, charset),
                        URLEncoder.encode(scope, charset));
  URL url = new URL(tokenEndPoint);
  HttpsURLConnection con = (HttpsURLConnection)url. openConnection();
  con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset="  + charset);
  con.setDoOutput(true);
  con.setRequestMethod("POST");
  OutputStream output = null;
  try {
    output = con.getOutputStream();
    output.write(query.getBytes(charset));
    output.flush();
  } finally {
    if (output != null) try {
      output.close();
    } catch (IOException logOrIgnore) {}
  }
  con.connect();
  System.out.println("response message is = " + con.getResponseMessage());
  // read the output from the server
  BufferedReader reader = null;
  StringBuilder stringBuilder;
  reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
  stringBuilder = new StringBuilder();
  String line = null;
  try {
    while ((line = reader.readLine()) != null) {
      stringBuilder.append(line + "\n");
    }
  } finally {
    if (reader != null) try {
      reader.close();
    } catch (IOException logOrIgnore) {}
  }
  String tokenResponse = stringBuilder.toString();
  System.out.println ("response is = " + tokenResponse);
  JSONObject json = JSONObject.parse(tokenResponse);
  if (json.containsKey("access_token")) {
    accessToken = (String)json.get("access_token");
    this.accessToken = accessToken;
  }
  if (json.containsKey("refresh_token")) {
    refreshToken = (String)json.get("refresh_token");
  }
  //sendRequestForAccessToken(query);
  if (accessToken != null) {
    String query = String.format("access_token=%s",
                                 URLEncoder.encode(accessToken, charset));
    URL urlResource = new URL(resourceEndPoint);
    HttpsURLConnection conn = (HttpsURLConnection) urlResource.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
    conn.setDoOutput(true);
    output = null;
    try {
      output = conn.getOutputStream();
      output.write(query.getBytes(charset));
      output.flush();
    } finally {
      if (output != null) try {
        output.close();
      } catch (IOException logOrIgnore) {}
    }
    conn.connect();
    System.out.println("response to the resource request is = " + conn.getResponseMessage ());
    reader = null;
    if(conn.getResponseCode()>=200 && conn.getResponseCode() < 400) {
      reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      stringBuilder = new StringBuilder();
      String line = null;
      try {
        while ((line = reader.readLine()) != null) {
          stringBuilder.append(line + "\n");
        }
      } finally {
        if (reader != null) try {
          reader.close();
        } catch (IOException  logOrIgnore) {}
      }
      System.out.println ("response message to the request resource is = " +  stringBuilder.toString());
    } else {
      isValidResponse = false;
    }
  }
}

Implicit grant flow

The OAuth client requests an access token from the WebSphere Application Server OAuth 2.0 authorization endpoint by adding token response_type, redirect_url, client_id, scope, and state as request parameters.
https://host_name:port_number/oauth2/endpoint/provider_name/authorize
or
https://host_name:port_number/oauth2/declarativeEndpoint/provider_name/authorize
The following example shows the construction of the URI when using implicit grant:
if (isImplicit) {
  param1 = "token";
  String query = String.format("response_type=%s&
                               client_id=%s&
                               state=%s&
                               redirect_uri=%s&
                               scope=%s",
                               URLEncoder.encode(param1, charset),
                               URLEncoder.encode(clientId, charset),
                               URLEncoder.encode(state, charset),
                               URLEncoder.encode(redirectURI, charset),
                               URLEncoder.encode(scope, charset));
  String s = authorizationEndPoint + "?" + query;
  System.out.println("Visit: " + s + "\nand grant permission");
  System.out.print("Now enter the access token you have received in redirect uri :");
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  accessToken = br.readLine();
  if (accessToken != null) {
    // send Resource Request using the access token
  }
}

Client credential flow

The OAuth client accesses the token endpoint by using the client ID and client secret, and exchanges for an access token for future resource requests. In this flow, the client accesses the token endpoint by adding client_credentials grant type, client_id, and client_secret as request parameters.
https://host_name:port_number/oauth2/endpoint/provider_name/token
The following example shows the construction of the URI when using client credential:
if (isClientCredentials){
  param1 = "client_credentials";
  String query = String.format("grant_type=%s&
                               scope=%s&
                               client_id=%s&
                               client_secret=%s",
                               URLEncoder.encode(param1, charset),
                               URLEncoder.encode(scope, charset),
                               URLEncoder.encode(clientId, charset),
                               URLEncoder.encode(clientSecret, charset));
  accessToken = sendRequestForAccessToken(query);
  if (accessToken != null)	{
    //send Resource Request using (accessToken);
  }
}

Resource owner password credentials flow

The Resource Owner Password Credentials flow passes the user ID and password of the resource owner to the token endpoint directly. In this flow, The OAuth client accesses the token endpoint by adding password grant type, client_id, client_secret, username, password, scope, and state as request parameters.
https://host_name:port_number/oauth2/endpoint/provider_name/token
The following example shows the construction of the URI when using resource owner password:
if (isResourceOwnerCredentials) {
  param1 = "password";
  String query = String.format("grant_type=%s&
                               username=%s&
                               password=%s&
                               scope=%s&
                               client_id=%s&
                               client_secret=%s",
                               URLEncoder.encode(param1, charset),
                               URLEncoder.encode(resOwnerName, charset),
                               URLEncoder.encode(resOwnerPassword, charset),
                               URLEncoder.encode(scope, charset),
                               URLEncoder.encode(clientId, charset),
                               URLEncoder.encode(clientSecret, charset));
  accessToken = sendRequestForAccessToken(query);
  if (accessToken != null)	{
    //send Resource Request using (accessToken);
  }
}
If the access token is expired, then the refresh token can be sent to get a valid access token. The following example shows how to send a refresh token:
if(isAccessToken) {
  if (this.accessToken != null) {
    if (!sendResourceRequest(this.accessToken)) {
      // resource request failed...
      //get refresh token
      param1 = "refresh_token";
      String query = String.format("grant_type=%s&
                                   client_id=%s&
                                   client_secret=%s&
                                   refresh_token=%s&
                                   scope=%s",
                                   URLEncoder.encode(param1, charset),
                                   URLEncoder.encode(clientId, charset),
                                   URLEncoder.encode(clientSecret, charset),
                                   URLEncoder.encode(this.refreshToken, charset),
                                   URLEncoder.encode(scope, charset));
      accessToken = sendRequestForAccessToken(query);
      if (accessToken != null) {
        sendResourceRequest(accessToken);
      }
    }
  }
}