Integrate the OAuth Authorization Code

This topic describes the Java SDK OAuth Authorization Code flow integration.

Overview

Confidential and public clients use the Authorization Code flow type to exchange an authorization
code for an access token.
In this flow, the client redirects the user to a CyberArk Identity popup where the user enters their credentials and grants access. The OAuth server returns an authorization code to the client. The client then sends a request to the OAuth server to obtain a bearer authorization token, and includes the authorization code in this request. The OAuth server returns the authorization and refresh token to the client for use in accessing subsequent endpoints. For more information see the Authorization Code Flow RFC.

It is recommended that all clients use the PKCE extension with this flow as well to provide better security.

Before you begin

Integrate the SDK

Follow the steps below to use this SDK to get the access_token.

Step 1: Configure an OAuth client instance using the Java SDK

  • Import the SDK as specified in the Before you get started section.
  • Pass the required parameters to create an OAuthClient instance.
import com.cyberark.client.OAuthClient;

// client secret parameter must be passed in Authorization Code grant type
OAuthClient oauthClient = new OAuthClient(YOUR_TENANT_URL, YOUR_OAUTH_APPLICATION_ID, YOUR_USER_ID, YOUR_USER_PASSWORD);

Step 2: Build an authorize URL

Create an AuthorizeUrlBuilder to authenticate the user with the CyberArk Identity provider. The redirectUri must be white-listed in the Redirect destinations section under the General Usage section of the OAuth client application.

Using the oauthClient instance, call the following builder methods.

AuthorizeUrlBuilder authorizeUrlBuilder = oauthClient.authorizeUrl(YOUR_REDIRECT_URL)
    .setResponseType("code")
    .setScope(YOUR_SCOPE);

// To get authorize URL
String authURL = authorizeUrlBuilder.build();
https://YOUR_TENANT_URL/OAuth2/Authorize/YOUR_OAUTH_APPLICATION_ID?redirect_uri=YOUR_REDIRECT_URI&client_id=YOUR_USER_ID&client_secret=YOUR_USER_PASSWORD&scope=YOUR_SCOPE&response_type=code

Redirect to the authorize URL obtained above and post authentication with CyberArk Identity. In case of unauthentication, receive the code as part of the redirected URL mentioned above.

https://YOUR_REDIRECT_URI?responseType=code&code=YOUR_CODE

Step 3: Exchange the code with the token

Use the oauthClient instance to exchange the code received in the previous step to get the access_token.

TokenRequest tokenRequest = oauthClient.requestToken(YOUR_CODE, YOUR_REDIRECT_URL)
    .setGrantType("authorization_code");

TokenHolder tokenHolder = tokenRequest.execute();
{
  access_token: "YOUR_ACCESS_TOKEN",
  expires_in: 18000,
  refresh_token: "YOUR_REFRESH_TOKEN",
  scope: "all",
  token_type: "Bearer"
}

Common Methods

For common methods, such as refreshToken, revokeToken and claims, refer to CyberArk Identity Java SDK reference.