Sample code for 30+ languages & platforms
CkJava Requires Chilkat v11.0.0+

Jira Cloud: Obtain an OAuth2 Access Token

See more Jira Examples

Authorize an integration, save the access and refresh tokens, and list the sites available to the token. Register an OAuth2 (3LO) app in the Atlassian developer console, enable the Jira API scopes, and register the exact callback http://127.0.0.1:3017/. Run this interactive example on the same computer as the browser.

This demonstrates Atlassian's documented confidential-client flow for a privately operated integration. The client secret must remain confidential; do not embed it in an application distributed to users. A distributed client should use an application backend to perform the confidential token exchange. This example does not implement a public-client PKCE flow.

The core scopes shown cover the platform examples. Jira Software and Service Management have additional endpoint-specific scopes: add the needed scopes in the developer console and the authorization request, then obtain consent again. offline_access requests a rotating refresh token. Store the token file in a private directory, never print its contents, and select the intended site explicitly rather than assuming the first returned site is correct.

Targets Jira Cloud. Jira Data Center has a separate REST API and may require different paths, authentication, or payloads.

Atlassian REST API documentation

Chilkat CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    CkOAuth2 oauth = new CkOAuth2();
    oauth.put_AuthorizationEndpoint("https://auth.atlassian.com/authorize");
    oauth.put_TokenEndpoint("https://auth.atlassian.com/oauth/token");
    oauth.put_ClientId("YOUR_CLIENT_ID");
    oauth.put_ClientSecret("YOUR_CLIENT_SECRET");
    oauth.put_LocalHost("127.0.0.1");
    oauth.put_ListenPort(3017);
    //  Register exactly http://127.0.0.1:3017/ in the developer console.
    //  Keep scope on the authorization request, not the authorization-code exchange.
    oauth.put_UncommonOptions("NO_OAUTH2_SCOPE");
    oauth.put_UseBasicAuth(false);
    oauth.put_CodeChallenge(false);
    oauth.put_Scope("read:jira-work write:jira-work read:jira-user offline_access");
    success = oauth.AddAuthQueryParam("audience","api.atlassian.com");
    if (success != true) {
        System.out.println("Operation failed.");
        return;
        }

    success = oauth.AddAuthQueryParam("prompt","consent");
    if (success != true) {
        System.out.println("Operation failed.");
        return;
        }

    //  Chilkat generates state and validates it when the browser redirects back.
    String authUrl = oauth.startAuth();
    if (oauth.get_LastMethodSuccess() != true) {
        System.out.println("Could not start the local authorization listener.");
        return;
        }

    success = oauth.LaunchBrowser(authUrl);
    if (success != true) {
        oauth.Cancel();
        System.out.println("Could not open the system browser.");
        return;
        }

    int waited = 0;
    while (((oauth.get_AuthFlowState() < 3) && (waited < 180000))) {
        oauth.SleepMs(200);
        waited = waited+200;
        }

    if (oauth.get_AuthFlowState() < 3) {
        oauth.Cancel();
        System.out.println("Authorization timed out.");
        return;
        }

    if (oauth.get_AuthFlowState() != 3) {
        System.out.println("Authorization did not complete. Flow state: " + oauth.get_AuthFlowState());
        return;
        }

    CkJsonObject token = new CkJsonObject();
    success = token.Load(oauth.accessTokenResponse());
    if (success != true) {
        System.out.println("Could not parse the token response.");
        return;
        }

    if ((token.JsonTypeOf("access_token") != 1) || (token.StringOfEquals("access_token","",true) == true)) {
        System.out.println("Missing value: access_token");
        return;
        }

    if ((token.JsonTypeOf("refresh_token") != 1) || (token.StringOfEquals("refresh_token","",true) == true)) {
        System.out.println("Missing value: refresh_token");
        return;
        }

    //  Use a private working directory accessible only to this application/user.
    success = token.WriteFile("jira-token.json");
    if (success != true) {
        System.out.println("Could not save the token file.");
        return;
        }

    CkHttp http = new CkHttp();
    http.put_RequireSslCertVerify(true);
    http.put_AuthToken(token.stringOf("access_token"));
    http.put_Accept("application/json");
    CkHttpResponse resp = new CkHttpResponse();
    success = http.HttpNoBody("GET","https://api.atlassian.com/oauth/token/accessible-resources",resp);
    if (resp.get_StatusCode() == 0) {
        System.out.println("No HTTP response was received. Check connectivity and TLS settings.");
        return;
        }

    if ((success != true) || (resp.get_StatusCode() < 200) || (resp.get_StatusCode() >= 300)) {
        System.out.println("Request failed. HTTP " + resp.get_StatusCode());
        if (resp.get_StatusCode() == 429) {
            System.out.println("Rate limited. Retry-After: " + resp.getHeaderField("Retry-After"));
            }

        return;
        }

    CkJsonArray sites = new CkJsonArray();
    success = sites.Load(resp.bodyStr());
    if (success != true) {
        System.out.println("Expected an array of accessible sites.");
        return;
        }

    int i = 0;
    CkJsonObject site = new CkJsonObject();
    while ((i < sites.get_Size())) {
        site = sites.ObjectAt(i);
        if (sites.get_LastMethodSuccess() != true) {
            System.out.println("Invalid site entry.");
            return;
            }

        System.out.println(site.stringOf("name") + "  " + site.stringOf("url") + "  Cloud ID: " + site.stringOf("id"));

        i = i+1;
        }

    System.out.println("Tokens saved. Select the intended site's Cloud ID for subsequent API requests.");
  }
}