Chilkat Online Tools

Android / ForgeRock Identity Cloud Collection / Step 5: Introspect the Access Token

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;

    CkHttpRequest req = new CkHttpRequest();

    CkJsonObject jsonParam1 = new CkJsonObject();
    req.AddParam("token",jsonParam1.emit());

    CkJsonObject jsonParam2 = new CkJsonObject();
    req.AddParam("client_id",jsonParam2.emit());

    req.AddHeader("Authorization","Bearer <access_token>");

    CkHttpResponse resp = http.PostUrlEncoded("https://<tenant-name>.forgeblocks.com/am/oauth2/realms/root/realms/alpha/introspect",req);
    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)

    // {
    //   "active": true,
    //   "scope": "manage",
    //   "realm": "/",
    //   "client_id": "forgerockDemoPublicClient",
    //   "user_id": "demo",
    //   "token_type": "Bearer",
    //   "exp": 1597324784,
    //   "sub": "demo",
    //   "iss": "http://openam.example.com:8080/openam/oauth2",
    //   "auth_level": 0,
    //   "authGrantId": "bdtxHp1kka6iin4Q2KpNgCfgcVs",
    //   "auditTrackingId": "037f02f9-d821-4f72-8563-c5050c40fdc3-53256",
    //   "expires_in": 3600
    // }

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

    boolean active = jResp.BoolOf("active");
    String scope = jResp.stringOf("scope");
    String realm = jResp.stringOf("realm");
    String client_id = jResp.stringOf("client_id");
    String user_id = jResp.stringOf("user_id");
    String token_type = jResp.stringOf("token_type");
    int exp = jResp.IntOf("exp");
    String v_sub = jResp.stringOf("sub");
    String iss = jResp.stringOf("iss");
    int auth_level = jResp.IntOf("auth_level");
    String authGrantId = jResp.stringOf("authGrantId");
    String auditTrackingId = jResp.stringOf("auditTrackingId");
    int expires_in = jResp.IntOf("expires_in");

  }

  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>"
	--data-urlencode 'token={{access_token}}'
	--data-urlencode 'client_id={{postmanPublicClientId}}'
https://<tenant-name>.forgeblocks.com/am/oauth2/realms/root/realms/alpha/introspect

Postman Collection Item JSON

{
  "name": "Step 5: Introspect the Access Token",
  "event": [
    {
      "listen": "test",
      "script": {
        "exec": [
          "// Tests",
          "",
          "const jsonData = JSON.parse(responseBody);",
          "",
          "pm.test(\"Status code is 200\", () => {",
          "  pm.expect(pm.response.code).to.eql(200);",
          "});",
          "",
          "pm.test(\"Response contains correct `client_id`.\", function () {",
          "    pm.expect(jsonData.client_id).to.eql(pm.collectionVariables.get(\"postmanPublicClientId\"));",
          "});",
          ""
        ],
        "type": "text/javascript"
      }
    }
  ],
  "request": {
    "method": "POST",
    "header": [
    ],
    "body": {
      "mode": "urlencoded",
      "urlencoded": [
        {
          "key": "token",
          "value": "{{access_token}}",
          "description": "Access token you want to introspect.",
          "type": "text"
        },
        {
          "key": "client_id",
          "value": "{{postmanPublicClientId}}",
          "description": "The ID of the Confidential OAuth Client.",
          "type": "text"
        }
      ]
    },
    "url": {
      "raw": "{{amUrl}}/oauth2{{realm}}/introspect",
      "host": [
        "{{amUrl}}"
      ],
      "path": [
        "oauth2{{realm}}",
        "introspect"
      ]
    },
    "description": "Retrieve metadata about the active access token, such as, approved scopes, the user that authorized the token, and the expiry time."
  },
  "response": [
    {
      "name": "Example",
      "originalRequest": {
        "method": "POST",
        "header": [
        ],
        "body": {
          "mode": "urlencoded",
          "urlencoded": [
            {
              "key": "token",
              "value": "{{access_token}}",
              "description": "Access token you want to introspect.",
              "type": "text"
            },
            {
              "key": "client_id",
              "value": "{{postmanPublicClientId}}",
              "description": "The ID of the Confidential OAuth Client.",
              "type": "text"
            }
          ]
        },
        "url": {
          "raw": "{{amUrl}}/oauth2{{realm}}/introspect",
          "host": [
            "{{amUrl}}"
          ],
          "path": [
            "oauth2{{realm}}",
            "introspect"
          ]
        }
      },
      "status": "OK",
      "code": 200,
      "_postman_previewlanguage": "json",
      "header": [
        {
          "key": "X-Frame-Options",
          "value": "SAMEORIGIN"
        },
        {
          "key": "X-Content-Type-Options",
          "value": "nosniff"
        },
        {
          "key": "Content-Type",
          "value": "application/json;charset=UTF-8"
        },
        {
          "key": "Content-Length",
          "value": "346"
        },
        {
          "key": "Date",
          "value": "Thu, 13 Aug 2020 12:20:17 GMT"
        }
      ],
      "cookie": [
      ],
      "body": "{\n    \"active\": true,\n    \"scope\": \"manage\",\n    \"realm\": \"/\",\n    \"client_id\": \"forgerockDemoPublicClient\",\n    \"user_id\": \"demo\",\n    \"token_type\": \"Bearer\",\n    \"exp\": 1597324784,\n    \"sub\": \"demo\",\n    \"iss\": \"http://openam.example.com:8080/openam/oauth2\",\n    \"auth_level\": 0,\n    \"authGrantId\": \"bdtxHp1kka6iin4Q2KpNgCfgcVs\",\n    \"auditTrackingId\": \"037f02f9-d821-4f72-8563-c5050c40fdc3-53256\",\n    \"expires_in\": 3600\n}"
    }
  ]
}