Ask a Question

How to get Access Token for OAuth 2.0 using client_credentials using java code?

avidCoder
Super Contributor

How to get Access Token for OAuth 2.0 using client_credentials using java code?

I have some API which requires access token to get the response. In postman we use OAuth 2.0 to get the access token by providing client username and password. In similar way, I want to fetch the new access token.

Here is the sample code which I have tried so far.

 

import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.lang.reflect.Type;
import javax.net.ssl.HttpsURLConnection;

// Google Gson Libraries used for Json Parsing
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class AuthGoogle {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
         String grantType = "client_credentials";
            String applicationID = "application";
            String username = "username";
            String password = "password";
            String url = "url_link";
            HttpsURLConnection httpConn = null;
            BufferedReader in = null;

            try {

                // Create the data to send
                StringBuilder data = new StringBuilder();
                data.append("grant_type=" + URLEncoder.encode(grantType, "UTF-8"));
                data.append("&client_id=" + URLEncoder.encode(applicationID, "UTF-8"));
                data.append("&username=" + URLEncoder.encode(username, "UTF-8"));
                data.append("&password=" + URLEncoder.encode(password, "UTF-8"));

                // Create a byte array of the data to be sent
                byte[] byteArray = data.toString().getBytes("UTF-8");

                // Setup the Request
                URL request = new URL(null, url,  new sun.net.www.protocol.https.Handler());
                httpConn = (HttpsURLConnection)request.openConnection();
                httpConn.setRequestMethod("POST");
                httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                httpConn.setRequestProperty("Content-Length", "" + byteArray.length);
                httpConn.setDoOutput(true);

                // Write data
                OutputStream postStream = httpConn.getOutputStream();
                postStream.write(byteArray, 0, byteArray.length);
                postStream.close();

                // Send Request & Get Response
                InputStreamReader reader = new InputStreamReader(httpConn.getInputStream());
                in = new BufferedReader(reader);

                // Get the Json reponse containing the Access Token
                String json = in.readLine();
                System.out.println("Json String = " + json);

                // Parse the Json response and retrieve the Access Token
                Gson gson = new Gson();
                Type mapType  = new TypeToken<Map<String,String>>(){}.getType();
                Map<String,String> ser = gson.fromJson(json, mapType);
                String accessToken = ser.get("access_token");
                System.out.println("Access Token = " + accessToken);

            } catch (java.io.IOException e) {

                // This exception will be raised if the server didn't return 200 - OK
                // Retrieve more information about the error
                System.out.println(e.getMessage());

            } finally {

                // Be sure to close out any resources or connections
                if (in != null) in.close();
                if (httpConn != null) httpConn.disconnect();
            }
        }

}

I am getting output as Connection refused: connect.

Another code I have tried is:-

import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.message.types.GrantType;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;

public class OltuJavaClient {

    public static final String TOKEN_REQUEST_URL = "url_link";
    public static final String CLIENT_ID = "client_id";
    public static final String CLIENT_SECRET = "client_pass";

    public static void main(String[] args) {
        try {
            OAuthClient client = new OAuthClient(new URLConnectionClient());

            OAuthClientRequest request =
                    OAuthClientRequest.tokenLocation(TOKEN_REQUEST_URL)
                    .setGrantType(GrantType.CLIENT_CREDENTIALS)
                    .setClientId(CLIENT_ID)
                    .setClientSecret(CLIENT_SECRET)
                    // .setScope() here if you want to set the token scope
                    .buildQueryMessage();
            request.addHeader("Accept", "application/json");
            request.addHeader("Content-Type", "application/json");
            request.addHeader("Authorization", base64EncodedBasicAuthentication());

            String token = client.accessToken(request, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class).getAccessToken();
            System.out.println(token.toString());

        } catch (Exception exn) {
            exn.printStackTrace();
        }
    }

    private static String base64EncodedBasicAuthentication() {
        // TODO Auto-generated method stub
        return null;
    }
}

Here I am getting this error:- OAuthProblemException{error='unsupported_response_type', description='Invalid response! Response body is not application/json encoded', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}

Can we do this way? Any leads would be appreciated.

10 REPLIES 10
NBorovykh
Moderator

Hello @avidCoder,

 

The easiest way to get an access token programmarically in ReadyAPI is:

1. Configure the OAuth 2.0 profile for a request and make sure that you can retrieve the token manually.

2018-09-10_13-07-26.png

2. If the selected flow requires some interaction with the internal browser, add the corresponding JavaScript code to the "Automation..." section to automate this interaction.

3.  Add the Groovy code which accesses the configured OAuth profile and runs the token retrieval method. 

 

Step #2 and #3 are described in details in this article: https://support.smartbear.com/readyapi/docs/projects/requests/auth/types/oauth2/automate/sample.html

 

Natalie
Customer Care Team

Did my reply answer your question? Give Kudos or Accept it as a Solution to help others.↓↓↓↓↓
Olga_T
SmartBear Alumni (Retired)

Hi all,

 

@NBorovykh, thank you for sharing your expertise! 

@avidCoder do the above steps work for you? Or, do you have any additional information for us?
We are looking forward to hearing from you,

 

 


Olga Terentieva
SmartBear Assistant Community Manager

avidCoder
Super Contributor

Yes, I found the solution for my query. I used springframework code to implement this. And it was just 6-7 lines of code. Thanks for the support.

Hello,

 

Am also looking for a solution to implement the access token.

I have the rest api which returns the access token. now i want to call that rest call in java inorder to get the access token, by passing grant type, username and password.

https://example.com/oauth2/token is the uri.

Coud you please share the piece of code or help me out with this how to achieve.

 

Thanks for your support,

Ashrey

Hello,

 

Can you please help me how to acheive .

I want to get access token from the rest api to access the resources from server. using grant type, user name, paasowrd. tried few methods but not successful.

avidCoder
Super Contributor

Hi Ashrey,

 

Please try below code to fecth the AuthToken and replace CLIENT-ID, CLIENT-SECRET and AUTHTOKEN-URL with your value:-

 

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

public String getAuthToken() {

        try {

            TrustStrategy trustStrategy = new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            };
            SSLConnectionSocketFactory sslsf = null;
            try {
                SSLContextBuilder builder = new SSLContextBuilder();
                builder.loadTrustMaterial(trustStrategy);
                sslsf = new SSLConnectionSocketFactory(
                        builder.build());
                CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
                        sslsf).build();
            } catch (NoSuchAlgorithmException | KeyManagementException e) {

            } catch (KeyStoreException e) {
                e.printStackTrace();
            }
            CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).build();

            Unirest.setHttpClient(client);
            HttpResponse<String> response = Unirest.post("https://CLIENT-ID:CLIENT-SECRET@AUTHTOKEN-URL?grant_type=client_credentials")
                    .header("cache-control", "no-cache")
                    .asString();

            JsonElement je = new JsonParser().parse(response.getBody());
            return je.getAsJsonObject().get("access_token").getAsString().toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

Let me know if you face any issue and Accept as a solution if it works for you.

Hello,

I dont have to sent client id and secret key in my api request.

the api call works fine in postman without client id and secret key.

the api call needs only grant type, user name, pwd to be send as body or header part. content type must be form-data-url encoded.i have attached the image of post man of the request reference.

Is it possible to get the access token without client key and secret as my cuctomer didnt share anything.

 

avidCoder
Super Contributor

I just referred the picture you attached, I guess you should mention grant_type as client_credentials if you have client_id and client_secret. You cannot fetch the access token without providing the client_id and client_secret for the grant_type as client_credentials to the best of my knowledge. Please refer this link for your understanding:-

 

https://stackoverflow.com/questions/34842895/difference-between-grant-type-client-credentials-and-gr...

https://community.servicenow.com/community?id=community_question&sys_id=5b968f25db1cdbc01dcaf3231f96...

Hello,

 

Thank you for the information.

I dont have the client id and client secret. the ready api is executable with the grant type password.

i also referred the docs from here :

https://docs.apigee.com/api-platform/security/oauth/implementing-password-grant-type 

 

Also i tried to execute your code whihc you have shared, but facing an error. added the imports and jar.

This is the line of code showing the error :    builder.loadTrustMaterial( trustStrategy);

The method loadTrustMaterial(org.apache.http.ssl.TrustStrategy) in the type SSLContextBuilder is not applicable for the arguments (org.apache.http.conn.ssl.TrustStrategy)

Is it due to version of jar/java?

 

Thanks for your support.

 

cancel
Showing results for 
Search instead for 
Did you mean: