Chilkat Online Tools

Swift / ForgeRock Identity Cloud Collection / Step 2: Introspect the Access Token

Back to Collection Items

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

    let http = CkoHttp()
    var success: Bool

    let req = CkoHttpRequest()

    let jsonParam1 = CkoJsonObject()
    req.AddParam("token", value: jsonParam1.Emit())

    let jsonParam2 = CkoJsonObject()
    req.AddParam("client_id", value: jsonParam2.Emit())

    let jsonParam3 = CkoJsonObject()
    req.AddParam("client_secret", value: jsonParam3.Emit())

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

    var resp: CkoHttpResponse? = http.PostUrlEncoded("https://<tenant-name>.forgeblocks.com/am/oauth2/realms/root/realms/alpha/introspect", req: req)
    if http.LastMethodSuccess == false {
        print("\(http.LastErrorText)")
        return
    }

    let sbResponseBody = CkoStringBuilder()
    resp!.GetBodySb(sbResponseBody)

    let jResp = CkoJsonObject()
    jResp.LoadSb(sbResponseBody)
    jResp.EmitCompact = false

    print("Response Body:")
    print("\(jResp.Emit())")

    var respStatusCode: Int = resp!.StatusCode.intValue
    print("Response Status Code = \(respStatusCode)")
    if respStatusCode >= 400 {
        print("Response Header:")
        print("\(resp!.Header)")
        print("Failed.")
        resp = nil
        return
    }

    resp = nil

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

    // {
    //   "active": true,
    //   "scope": "write",
    //   "realm": "/",
    //   "client_id": "forgerockDemoConfidentialClient",
    //   "user_id": "demo",
    //   "token_type": "Bearer",
    //   "exp": 1597324612,
    //   "sub": "demo",
    //   "iss": "http://openam.example.com:8080/openam/oauth2",
    //   "auth_level": 0,
    //   "authGrantId": "HAQs5GyHyZvbj_bOkdX9Ul03lh0",
    //   "auditTrackingId": "037f02f9-d821-4f72-8563-c5050c40fdc3-52010",
    //   "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

    var active: Bool = jResp.BoolOf("active")
    var scope: String? = jResp.StringOf("scope")
    var realm: String? = jResp.StringOf("realm")
    var client_id: String? = jResp.StringOf("client_id")
    var user_id: String? = jResp.StringOf("user_id")
    var token_type: String? = jResp.StringOf("token_type")
    var exp: Int = jResp.IntOf("exp").intValue
    var v_sub: String? = jResp.StringOf("sub")
    var iss: String? = jResp.StringOf("iss")
    var auth_level: Int = jResp.IntOf("auth_level").intValue
    var authGrantId: String? = jResp.StringOf("authGrantId")
    var auditTrackingId: String? = jResp.StringOf("auditTrackingId")
    var expires_in: Int = jResp.IntOf("expires_in").intValue

}

Curl Command

curl -X POST
	-H "Authorization: Bearer <access_token>"
	--data-urlencode 'token={{access_token}}'
	--data-urlencode 'client_id={{postmanConfidentialClientId}}'
	--data-urlencode 'client_secret={{postmanClientSecret}}'
https://<tenant-name>.forgeblocks.com/am/oauth2/realms/root/realms/alpha/introspect

Postman Collection Item JSON

{
  "name": "Step 2: 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(\"postmanConfidentialClientId\"));",
          "});",
          "",
          "",
          ""
        ],
        "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": "{{postmanConfidentialClientId}}",
          "description": "The ID of the Confidential OAuth Client.",
          "type": "text"
        },
        {
          "key": "client_secret",
          "value": "{{postmanClientSecret}}",
          "description": "The secret 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": "{{postmanConfidentialClientId}}",
              "description": "The ID of the Confidential OAuth Client.",
              "type": "text"
            },
            {
              "key": "client_secret",
              "value": "{{postmanClientSecret}}",
              "description": "The secret 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": "351"
        },
        {
          "key": "Date",
          "value": "Thu, 13 Aug 2020 12:17:03 GMT"
        }
      ],
      "cookie": [
      ],
      "body": "{\n    \"active\": true,\n    \"scope\": \"write\",\n    \"realm\": \"/\",\n    \"client_id\": \"forgerockDemoConfidentialClient\",\n    \"user_id\": \"demo\",\n    \"token_type\": \"Bearer\",\n    \"exp\": 1597324612,\n    \"sub\": \"demo\",\n    \"iss\": \"http://openam.example.com:8080/openam/oauth2\",\n    \"auth_level\": 0,\n    \"authGrantId\": \"HAQs5GyHyZvbj_bOkdX9Ul03lh0\",\n    \"auditTrackingId\": \"037f02f9-d821-4f72-8563-c5050c40fdc3-52010\",\n    \"expires_in\": 3600\n}"
    }
  ]
}