Chilkat Online Tools

Android / ForgeRock Identity Cloud Collection / Step 1: Obtain an SSO Token as a Demo User

Back to Collection Items

// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    CkHttp http = new CkHttp();
    boolean success;

    http.SetRequestHeader("Content-Type","application/json");
    http.SetRequestHeader("Accept-API-Version","resource=2.1");
    // Adds the "Authorization: Bearer <access_token>" header.
    http.put_AuthToken("<access_token>");
    http.SetRequestHeader("X-OpenAM-Username","{{postmanDemoUsername}}");
    http.SetRequestHeader("X-OpenAM-Password","{{postmanDemoPassword}}");

    CkHttpResponse resp = http.QuickRequest("POST","https://<tenant-name>.forgeblocks.com/am/json/realms/root/realms/alpha/authenticate?authIndexType=service&authIndexValue=PasswordGrant");
    if (http.get_LastMethodSuccess() == false) {
        Log.i(TAG, http.lastErrorText());
        return;
        }

    CkStringBuilder sbResponseBody = new CkStringBuilder();
    resp.GetBodySb(sbResponseBody);

    CkJsonObject jResp = new CkJsonObject();
    jResp.LoadSb(sbResponseBody);
    jResp.put_EmitCompact(false);

    Log.i(TAG, "Response Body:");
    Log.i(TAG, jResp.emit());

    int respStatusCode = resp.get_StatusCode();
    Log.i(TAG, "Response Status Code = " + String.valueOf(respStatusCode));
    if (respStatusCode >= 400) {
        Log.i(TAG, "Response Header:");
        Log.i(TAG, resp.header());
        Log.i(TAG, "Failed.");

        return;
        }

    // Sample JSON response:
    // (Sample code for parsing the JSON response is shown below)

    // {
    //   "tokenId": "HQP67NRnzJoBqi7NkEJCQMQIjXA.*AAJTSQACMDEAAlNLABxzUDdwa0VnaXo4ODhPZUE4QzhGREdaRDVmczQ9AAR0eXBlAANDVFMAAlMxAAA.*",
    //   "successUrl": "/openam/console",
    //   "realm": "/"
    // }

    // Sample code for parsing the JSON response...
    // Use this online tool to generate parsing code from sample JSON: Generate JSON Parsing Code

    String tokenId = jResp.stringOf("tokenId");
    String successUrl = jResp.stringOf("successUrl");
    String realm = jResp.stringOf("realm");

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}

Curl Command

curl -X POST
	-H "Authorization: Bearer <access_token>"
	-H "X-OpenAM-Username: {{postmanDemoUsername}}"
	-H "X-OpenAM-Password: {{postmanDemoPassword}}"
	-H "Content-Type: application/json"
	-H "Accept-API-Version: resource=2.1"
https://<tenant-name>.forgeblocks.com/am/json/realms/root/realms/alpha/authenticate?authIndexType=service&authIndexValue=PasswordGrant

Postman Collection Item JSON

{
  "name": "Step 1: Obtain an SSO Token as a Demo User",
  "event": [
    {
      "listen": "test",
      "script": {
        "exec": [
          "const jsonData = JSON.parse(responseBody);",
          "",
          "if(jsonData.tokenId && jsonData.tokenId != \"\"){",
          "    pm.globals.set(\"demoSSOToken\", jsonData.tokenId);",
          "}",
          "",
          "// Tests",
          "",
          "pm.test(\"Status code is 200\", () => {",
          "  pm.expect(pm.response.code).to.eql(200);",
          "});",
          "",
          "pm.test(\"Response contains tokenId\", function () {",
          "    pm.expect(jsonData.tokenId).to.be.a(\"string\");",
          "});",
          ""
        ],
        "type": "text/javascript"
      }
    },
    {
      "listen": "prerequest",
      "script": {
        "exec": [
          ""
        ],
        "type": "text/javascript"
      }
    }
  ],
  "protocolProfileBehavior": {
    "disableCookies": false,
    "followOriginalHttpMethod": true,
    "removeRefererHeaderOnRedirect": true
  },
  "request": {
    "method": "POST",
    "header": [
      {
        "description": "Username for the demo user.",
        "key": "X-OpenAM-Username",
        "value": "{{postmanDemoUsername}}"
      },
      {
        "description": "Password for the demo user.",
        "key": "X-OpenAM-Password",
        "value": "{{postmanDemoPassword}}"
      },
      {
        "description": "The media type of the resource.",
        "key": "Content-Type",
        "value": "application/json"
      },
      {
        "description": "This collection documents version 2.1 of the authentication resource.",
        "key": "Accept-API-Version",
        "value": "resource=2.1"
      }
    ],
    "url": {
      "raw": "{{amUrl}}/json{{realm}}/authenticate?authIndexType=service&authIndexValue=PasswordGrant",
      "host": [
        "{{amUrl}}"
      ],
      "path": [
        "json{{realm}}",
        "authenticate"
      ],
      "query": [
        {
          "key": "authIndexType",
          "value": "service"
        },
        {
          "key": "authIndexValue",
          "value": "PasswordGrant"
        }
      ]
    },
    "description": "Log in to the authorization server using the credentials of the demo user.\n\nNote: delete your cookies before using this call.\n\n"
  },
  "response": [
    {
      "name": "Example",
      "originalRequest": {
        "method": "POST",
        "header": [
          {
            "description": "Username for the demo user.",
            "key": "X-OpenAM-Username",
            "value": "{{postmanDemoUsername}}"
          },
          {
            "description": "Password for the demo user.",
            "key": "X-OpenAM-Password",
            "value": "{{postmanDemoPassword}}"
          },
          {
            "description": "The media type of the resource.",
            "key": "Content-Type",
            "value": "application/json"
          },
          {
            "description": "This collection documents version 2.1 of the authentication resource.",
            "key": "Accept-API-Version",
            "value": "resource=2.1"
          }
        ],
        "url": {
          "raw": "{{amUrl}}/json{{realm}}/authenticate",
          "host": [
            "{{amUrl}}"
          ],
          "path": [
            "json{{realm}}",
            "authenticate"
          ]
        }
      },
      "status": "OK",
      "code": 200,
      "_postman_previewlanguage": "json",
      "header": [
        {
          "key": "X-Frame-Options",
          "value": "SAMEORIGIN"
        },
        {
          "key": "X-Content-Type-Options",
          "value": "nosniff"
        },
        {
          "key": "Cache-Control",
          "value": "private"
        },
        {
          "key": "Cache-Control",
          "value": "no-cache, no-store, must-revalidate"
        },
        {
          "key": "Set-Cookie",
          "value": "amlbcookie=01; Path=/; Domain=example.com; HttpOnly"
        },
        {
          "key": "Set-Cookie",
          "value": "iPlanetDirectoryPro=sOpI1RvbCgvlQk.*AAJTSQACMDEA.*; Path=/; Domain=example.com; HttpOnly"
        },
        {
          "key": "Content-API-Version",
          "value": "resource=2.1"
        },
        {
          "key": "Expires",
          "value": "0"
        },
        {
          "key": "Pragma",
          "value": "no-cache"
        },
        {
          "key": "Content-Type",
          "value": "application/json"
        },
        {
          "key": "Content-Length",
          "value": "167"
        },
        {
          "key": "Date",
          "value": "Thu, 13 Aug 2020 12:15:01 GMT"
        }
      ],
      "cookie": [
      ],
      "body": "{\n    \"tokenId\": \"HQP67NRnzJoBqi7NkEJCQMQIjXA.*AAJTSQACMDEAAlNLABxzUDdwa0VnaXo4ODhPZUE4QzhGREdaRDVmczQ9AAR0eXBlAANDVFMAAlMxAAA.*\",\n    \"successUrl\": \"/openam/console\",\n    \"realm\": \"/\"\n}"
    }
  ]
}