Chilkat Online Tools

unicodeC / ForgeRock Identity Cloud Collection / Step 2c: Handle Choice Callback

Back to Collection Items

#include <C_CkHttpW.h>
#include <C_CkJsonObjectW.h>
#include <C_CkHttpResponseW.h>
#include <C_CkStringBuilderW.h>

void ChilkatSample(void)
    {
    HCkHttpW http;
    BOOL success;
    HCkJsonObjectW json;
    HCkHttpResponseW resp;
    HCkStringBuilderW sbResponseBody;
    HCkJsonObjectW jResp;
    int respStatusCode;
    const wchar_t *tokenId;
    const wchar_t *successUrl;
    const wchar_t *realm;

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

    http = CkHttpW_Create();

    // Use this online tool to generate code from sample JSON: Generate Code to Create JSON

    // The following JSON is sent in the request body.

    // {
    //   "authId": "{{authId}}",
    //   "callbacks": [
    //     {
    //       "type": "ChoiceCallback",
    //       "output": [
    //         {
    //           "name": "prompt",
    //           "value": "Succeed?"
    //         },
    //         {
    //           "name": "choices",
    //           "value": [
    //             "Yes",
    //             "No"
    //           ]
    //         },
    //         {
    //           "name": "defaultChoice",
    //           "value": 0
    //         }
    //       ],
    //       "input": [
    //         {
    //           "name": "IDToken1",
    //           "value": 0
    //         }
    //       ]
    //     }
    //   ]
    // }

    json = CkJsonObjectW_Create();
    CkJsonObjectW_UpdateString(json,L"authId",L"{{authId}}");
    CkJsonObjectW_UpdateString(json,L"callbacks[0].type",L"ChoiceCallback");
    CkJsonObjectW_UpdateString(json,L"callbacks[0].output[0].name",L"prompt");
    CkJsonObjectW_UpdateString(json,L"callbacks[0].output[0].value",L"Succeed?");
    CkJsonObjectW_UpdateString(json,L"callbacks[0].output[1].name",L"choices");
    CkJsonObjectW_UpdateString(json,L"callbacks[0].output[1].value[0]",L"Yes");
    CkJsonObjectW_UpdateString(json,L"callbacks[0].output[1].value[1]",L"No");
    CkJsonObjectW_UpdateString(json,L"callbacks[0].output[2].name",L"defaultChoice");
    CkJsonObjectW_UpdateInt(json,L"callbacks[0].output[2].value",0);
    CkJsonObjectW_UpdateString(json,L"callbacks[0].input[0].name",L"IDToken1");
    CkJsonObjectW_UpdateInt(json,L"callbacks[0].input[0].value",0);

    CkHttpW_SetRequestHeader(http,L"Content-Type",L"application/json");
    CkHttpW_SetRequestHeader(http,L"Accept-API-Version",L"resource=2.0, protocol=1.0");

    resp = CkHttpW_PostJson3(http,L"https://<tenant-name>.forgeblocks.com/am/json/realms/root/realms/alpha/authenticate?authIndexType=service&authIndexValue=Login",L"application/json",json);
    if (CkHttpW_getLastMethodSuccess(http) == FALSE) {
        wprintf(L"%s\n",CkHttpW_lastErrorText(http));
        CkHttpW_Dispose(http);
        CkJsonObjectW_Dispose(json);
        return;
    }

    sbResponseBody = CkStringBuilderW_Create();
    CkHttpResponseW_GetBodySb(resp,sbResponseBody);

    jResp = CkJsonObjectW_Create();
    CkJsonObjectW_LoadSb(jResp,sbResponseBody);
    CkJsonObjectW_putEmitCompact(jResp,FALSE);

    wprintf(L"Response Body:\n");
    wprintf(L"%s\n",CkJsonObjectW_emit(jResp));

    respStatusCode = CkHttpResponseW_getStatusCode(resp);
    wprintf(L"Response Status Code = %d\n",respStatusCode);
    if (respStatusCode >= 400) {
        wprintf(L"Response Header:\n");
        wprintf(L"%s\n",CkHttpResponseW_header(resp));
        wprintf(L"Failed.\n");
        CkHttpResponseW_Dispose(resp);
        CkHttpW_Dispose(http);
        CkJsonObjectW_Dispose(json);
        CkStringBuilderW_Dispose(sbResponseBody);
        CkJsonObjectW_Dispose(jResp);
        return;
    }

    CkHttpResponseW_Dispose(resp);

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

    // {
    //   "tokenId": "N60dPV99pcqVVI.*AAJTSQACMDEAAANDVFMAAlMxAAA.*",
    //   "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

    // Chilkat functions returning "const char *" return a pointer to temporary internal memory owned and managed by Chilkat.

    tokenId = CkJsonObjectW_stringOf(jResp,L"tokenId");
    successUrl = CkJsonObjectW_stringOf(jResp,L"successUrl");
    realm = CkJsonObjectW_stringOf(jResp,L"realm");


    CkHttpW_Dispose(http);
    CkJsonObjectW_Dispose(json);
    CkStringBuilderW_Dispose(sbResponseBody);
    CkJsonObjectW_Dispose(jResp);

    }

Curl Command

curl -X POST
	-H "Content-Type: application/json"
	-H "Accept-API-Version: resource=2.0, protocol=1.0"
	-d '{
    "authId": "{{authId}}",
    "callbacks": [
        {
            "type": "ChoiceCallback",
            "output": [
                {
                    "name": "prompt",
                    "value": "Succeed?"
                },
                {
                    "name": "choices",
                    "value": [
                        "Yes",
                        "No"
                    ]
                },
                {
                    "name": "defaultChoice",
                    "value": 0
                }
            ],
            "input": [
                {
                    "name": "IDToken1",
                    "value": 0
                }
            ]
        }
    ]
}'
https://<tenant-name>.forgeblocks.com/am/json/realms/root/realms/alpha/authenticate?authIndexType=service&authIndexValue=Login

Postman Collection Item JSON

{
  "name": "Step 2c: Handle Choice Callback",
  "event": [
    {
      "listen": "test",
      "script": {
        "exec": [
          "const JSONResponse = JSON.parse(responseBody);",
          "",
          "// Did request have a callback?",
          "if(JSONResponse.authId && JSONResponse.authId != \"\")",
          "{",
          "  // Set `authId` variable",
          "  pm.globals.set(\"authId\", JSONResponse.authId);",
          "  ",
          "  // Determine next request based on detected callbacks",
          "  frUtils.detectCallbacks(responseBody);",
          "}",
          "",
          "// Did request return SSO Token?",
          "if(JSONResponse.tokenId && JSONResponse.tokenId != \"\")",
          "{",
          "  // Set `demoSSOToken` variable",
          "  pm.globals.set(\"demoSSOToken\", JSONResponse.tokenId);",
          "",
          "  // Remove `authId` variable",
          "  pm.globals.unset(\"authId\");",
          "  ",
          "  // Skip to session info request",
          "  postman.setNextRequest(\"Step 3: Get Session Info\");",
          "}",
          "",
          "// Tests",
          "",
          "pm.test(\"Status code is 200\", () => {",
          "  pm.expect(pm.response.code).to.eql(200);",
          "});",
          "",
          "pm.test(\"Response contains tokenId or authId\", function () {",
          "    pm.expect(JSONResponse).to.have.any.keys('tokenId', 'authId');",
          "});",
          ""
        ],
        "type": "text/javascript"
      }
    }
  ],
  "protocolProfileBehavior": {
    "disableCookies": true
  },
  "request": {
    "method": "POST",
    "header": [
      {
        "key": "Content-Type",
        "value": "application/json",
        "description": "Specifies that the `/json/authenticate` endpoint uses JSON format for requests."
      },
      {
        "key": "Accept-API-Version",
        "value": "resource=2.0, protocol=1.0",
        "description": "Specifies the version of the `/json/authenticate` endpoint to use."
      }
    ],
    "body": {
      "mode": "raw",
      "raw": "{\n    \"authId\": \"{{authId}}\",\n    \"callbacks\": [\n        {\n            \"type\": \"ChoiceCallback\",\n            \"output\": [\n                {\n                    \"name\": \"prompt\",\n                    \"value\": \"Succeed?\"\n                },\n                {\n                    \"name\": \"choices\",\n                    \"value\": [\n                        \"Yes\",\n                        \"No\"\n                    ]\n                },\n                {\n                    \"name\": \"defaultChoice\",\n                    \"value\": 0\n                }\n            ],\n            \"input\": [\n                {\n                    \"name\": \"IDToken1\",\n                    \"value\": 0\n                }\n            ]\n        }\n    ]\n}",
      "options": {
        "raw": {
          "language": "json"
        }
      }
    },
    "url": {
      "raw": "{{amUrl}}/json{{realm}}/authenticate?authIndexType=service&authIndexValue={{loginJourney}}",
      "host": [
        "{{amUrl}}"
      ],
      "path": [
        "json{{realm}}",
        "authenticate"
      ],
      "query": [
        {
          "key": "authIndexType",
          "value": "service",
          "description": "Allows the request to configure the service (for example, an authentication tree) to use for this request."
        },
        {
          "key": "authIndexValue",
          "value": "{{loginJourney}}",
          "description": "Specifies the name of the service to use for this request.\nOverride this value using the `amAuthenticationTree` Postman variable."
        }
      ]
    },
    "description": "To respond to a callback, send back the whole JSON object with the missing `input` values filled.\n\nThis request shows how to respond to the `ChoiceCallback` callback."
  },
  "response": [
    {
      "name": "Success - authentication complete",
      "originalRequest": {
        "method": "POST",
        "header": [
          {
            "key": "Content-Type",
            "value": "application/json",
            "description": "Specifies that the `/json/authenticate` endpoint uses JSON format for requests."
          },
          {
            "key": "Accept-API-Version",
            "value": "resource=2.0, protocol=1.0",
            "description": "Specifies the version of the `/json/authenticate` endpoint to use."
          }
        ],
        "body": {
          "mode": "raw",
          "raw": "{\n    \"authId\": \"{{authId}}\",\n    \"callbacks\": [\n        {\n            \"type\": \"ChoiceCallback\",\n            \"output\": [\n                {\n                    \"name\": \"prompt\",\n                    \"value\": \"Succeed?\"\n                },\n                {\n                    \"name\": \"choices\",\n                    \"value\": [\n                        \"Yes\",\n                        \"No\"\n                    ]\n                },\n                {\n                    \"name\": \"defaultChoice\",\n                    \"value\": 0\n                }\n            ],\n            \"input\": [\n                {\n                    \"name\": \"IDToken1\",\n                    \"value\": 0\n                }\n            ]\n        }\n    ]\n}",
          "options": {
            "raw": {
              "language": "json"
            }
          }
        },
        "url": {
          "raw": "{{amUrl}}/json{{realm}}/authenticate?authIndexType=service&authIndexValue={{loginJourney}}",
          "host": [
            "{{amUrl}}"
          ],
          "path": [
            "json{{realm}}",
            "authenticate"
          ],
          "query": [
            {
              "key": "authIndexType",
              "value": "service",
              "description": "Allows the request to configure the service (for example, an authentication tree) to use for this request."
            },
            {
              "key": "authIndexValue",
              "value": "{{loginJourney}}",
              "description": "Specifies the name of the service to use for this request.\nOverride this value using the `amAuthenticationTree` Postman variable."
            }
          ]
        }
      },
      "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": "iPlanetDirectoryPro=N60dPVcmOADQN170-8799pcqVVI.*AAJTSQACMDEAAlNLABw5QThIM0ZJd3RKcmNyWWYxSzlPaGhzcllsUXM9AAR0eXBlAANDVFMAAlMxAAA.*; Path=/; Domain=example.com; HttpOnly"
        },
        {
          "key": "Set-Cookie",
          "value": "amlbcookie=01; 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": "Wed, 12 Aug 2020 14:10:41 GMT"
        }
      ],
      "cookie": [
      ],
      "body": "{\n    \"tokenId\": \"N60dPV99pcqVVI.*AAJTSQACMDEAAANDVFMAAlMxAAA.*\",\n    \"successUrl\": \"/openam/console\",\n    \"realm\": \"/\"\n}"
    }
  ]
}