Chilkat Online Tools

unicodeC / ForgeRock Identity Cloud Collection / Step 2: Get Authorization Code

Back to Collection Items

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

void ChilkatSample(void)
    {
    HCkHttpW http;
    BOOL success;
    HCkHttpRequestW req;
    HCkJsonObjectW jsonParam3;
    HCkJsonObjectW jsonParam4;
    HCkJsonObjectW jsonParam6;
    HCkHttpResponseW resp;
    HCkStringBuilderW sbResponseBody;
    HCkJsonObjectW jResp;
    int respStatusCode;
    const wchar_t *Client_id;
    const wchar_t *Code;
    const wchar_t *Iss;
    const wchar_t *data;
    const wchar_t *Accept;
    const wchar_t *Accept_Encoding;
    const wchar_t *Cookie;
    const wchar_t *Host;
    const wchar_t *Referer;
    const wchar_t *User_Agent;
    const wchar_t *X_Amzn_Trace_Id;
    const wchar_t *json;
    const wchar_t *method;
    const wchar_t *origin;
    const wchar_t *url;

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

    http = CkHttpW_Create();

    req = CkHttpRequestW_Create();
    CkHttpRequestW_AddParam(req,L"scope",L"write");
    CkHttpRequestW_AddParam(req,L"response_type",L"code");

    jsonParam3 = CkJsonObjectW_Create();
    CkHttpRequestW_AddParam(req,L"client_id",CkJsonObjectW_emit(jsonParam3));

    jsonParam4 = CkJsonObjectW_Create();
    CkHttpRequestW_AddParam(req,L"redirect_uri",CkJsonObjectW_emit(jsonParam4));
    CkHttpRequestW_AddParam(req,L"decision",L"allow");

    jsonParam6 = CkJsonObjectW_Create();
    CkHttpRequestW_AddParam(req,L"csrf",CkJsonObjectW_emit(jsonParam6));
    CkHttpRequestW_AddParam(req,L"state",L"abc123");
    CkHttpRequestW_AddParam(req,L"service",L"PasswordGrant");

    CkHttpRequestW_AddHeader(req,L"Authorization",L"Bearer <access_token>");
    CkHttpRequestW_AddHeader(req,L"Cookie",L"{{cookieName}}={{demoSSOToken}}");

    resp = CkHttpW_PostUrlEncoded(http,L"https://<tenant-name>.forgeblocks.com/am/oauth2/realms/root/realms/alpha/authorize",req);
    if (CkHttpW_getLastMethodSuccess(http) == FALSE) {
        wprintf(L"%s\n",CkHttpW_lastErrorText(http));
        CkHttpW_Dispose(http);
        CkHttpRequestW_Dispose(req);
        CkJsonObjectW_Dispose(jsonParam3);
        CkJsonObjectW_Dispose(jsonParam4);
        CkJsonObjectW_Dispose(jsonParam6);
        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);
        CkHttpRequestW_Dispose(req);
        CkJsonObjectW_Dispose(jsonParam3);
        CkJsonObjectW_Dispose(jsonParam4);
        CkJsonObjectW_Dispose(jsonParam6);
        CkStringBuilderW_Dispose(sbResponseBody);
        CkJsonObjectW_Dispose(jResp);
        return;
    }

    CkHttpResponseW_Dispose(resp);

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

    // {
    //   "args": {
    //     "client_id": "forgerockDemoConfidentialClient",
    //     "code": "oIQFFQ1S5Fxnqs5U_EMWxYEJktQ",
    //     "iss": "http://openam.example.com:8080/openam/oauth2"
    //   },
    //   "data": "",
    //   "files": {},
    //   "form": {},
    //   "headers": {
    //     "Accept": "*/*",
    //     "Accept-Encoding": "gzip, deflate, br",
    //     "Cookie": "amlbcookie=01; iPlanetDirectoryPro=sOpI1RvbCgvlQk.*AAJTSQACMDEA.*",
    //     "Host": "httpbin.org",
    //     "Referer": "http://openam.example.com:8080/openam/oauth2/realms/root/authorize",
    //     "User-Agent": "PostmanRuntime/7.26.3",
    //     "X-Amzn-Trace-Id": "Root=1-5f352dc7-0d6bd5fceafcd01e856febd2"
    //   },
    //   "json": null,
    //   "method": "GET",
    //   "origin": "5.65.200.229",
    //   "url": "https://httpbin.org/anything?code=oIQFFQ1S5Fxnqs5U_EMWxYEJktQ&iss=http:%2F%2Fopenam.example.com:8080%2Fopenam%2Foauth2&client_id=forgerockDemoConfidentialClient"
    // }

    // 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.

    Client_id = CkJsonObjectW_stringOf(jResp,L"args.client_id");
    Code = CkJsonObjectW_stringOf(jResp,L"args.code");
    Iss = CkJsonObjectW_stringOf(jResp,L"args.iss");
    data = CkJsonObjectW_stringOf(jResp,L"data");
    Accept = CkJsonObjectW_stringOf(jResp,L"headers.Accept");
    Accept_Encoding = CkJsonObjectW_stringOf(jResp,L"headers.Accept-Encoding");
    Cookie = CkJsonObjectW_stringOf(jResp,L"headers.Cookie");
    Host = CkJsonObjectW_stringOf(jResp,L"headers.Host");
    Referer = CkJsonObjectW_stringOf(jResp,L"headers.Referer");
    User_Agent = CkJsonObjectW_stringOf(jResp,L"headers.User-Agent");
    X_Amzn_Trace_Id = CkJsonObjectW_stringOf(jResp,L"headers.X-Amzn-Trace-Id");
    json = CkJsonObjectW_stringOf(jResp,L"json");
    method = CkJsonObjectW_stringOf(jResp,L"method");
    origin = CkJsonObjectW_stringOf(jResp,L"origin");
    url = CkJsonObjectW_stringOf(jResp,L"url");


    CkHttpW_Dispose(http);
    CkHttpRequestW_Dispose(req);
    CkJsonObjectW_Dispose(jsonParam3);
    CkJsonObjectW_Dispose(jsonParam4);
    CkJsonObjectW_Dispose(jsonParam6);
    CkStringBuilderW_Dispose(sbResponseBody);
    CkJsonObjectW_Dispose(jResp);

    }

Curl Command

curl -X POST
	-H "Authorization: Bearer <access_token>"
	-H "Cookie: {{cookieName}}={{demoSSOToken}}"
	--data-urlencode 'scope=write'
	--data-urlencode 'response_type=code'
	--data-urlencode 'client_id={{postmanConfidentialClientId}}'
	--data-urlencode 'redirect_uri={{redirect_uri}}'
	--data-urlencode 'decision=allow'
	--data-urlencode 'csrf={{demoSSOToken}}'
	--data-urlencode 'state=abc123'
	--data-urlencode 'service=PasswordGrant'
https://<tenant-name>.forgeblocks.com/am/oauth2/realms/root/realms/alpha/authorize

Postman Collection Item JSON

{
  "name": "Step 2: Get Authorization Code",
  "event": [
    {
      "listen": "test",
      "script": {
        "exec": [
          "const jsonData = pm.response.json();",
          "",
          "if(pm.response.code == 200)",
          "{",
          "    if(jsonData.args.code && jsonData.args.code != \"\") {",
          "        pm.globals.set(\"authorization_code\", jsonData.args.code);",
          "    }",
          "}",
          "",
          "// TESTS",
          "",
          "pm.test(\"Follow redirects is enabled in Postman (Status code not 302)\", () => {",
          "  // If response was 302, ensure Postman is following redirects.  ",
          "  pm.response.to.not.have.status(302);",
          "});",
          "",
          "pm.test(\"Response from httpbin contained `code` argument\", () => {",
          "    pm.expect(jsonData.args.code).to.be.a(\"string\");",
          "});"
        ],
        "type": "text/javascript"
      }
    }
  ],
  "protocolProfileBehavior": {
    "followRedirects": true
  },
  "request": {
    "method": "POST",
    "header": [
      {
        "key": "Cookie",
        "value": "{{cookieName}}={{demoSSOToken}}",
        "type": "text"
      }
    ],
    "body": {
      "mode": "urlencoded",
      "urlencoded": [
        {
          "key": "scope",
          "value": "write ",
          "description": "Strings that are presented to the user for approval and included in tokens so that the protected resource may make decisions about what to give access to.",
          "type": "text"
        },
        {
          "key": "response_type",
          "value": "code",
          "description": "Response types the client will support and use.",
          "type": "text"
        },
        {
          "key": "client_id",
          "value": "{{postmanConfidentialClientId}}",
          "description": "The ID of the Confidential OAuth Client.",
          "type": "text"
        },
        {
          "key": "redirect_uri",
          "value": "{{redirect_uri}}",
          "description": "The complete URI to which client redirects the user if the request is successful.",
          "type": "text"
        },
        {
          "key": "decision",
          "value": "allow",
          "description": "The complete URI to which client redirects the user if the request is successful.",
          "type": "text"
        },
        {
          "key": "csrf",
          "value": "{{demoSSOToken}}",
          "description": "SSO token of the demo user, to protect against cross-site request forgery.",
          "type": "text"
        },
        {
          "key": "state",
          "value": "abc123",
          "type": "text"
        },
        {
          "key": "service",
          "value": "PasswordGrant",
          "type": "text"
        }
      ]
    },
    "url": {
      "raw": "{{amUrl}}/oauth2{{realm}}/authorize",
      "host": [
        "{{amUrl}}"
      ],
      "path": [
        "oauth2{{realm}}",
        "authorize"
      ]
    },
    "description": "Get the authorization code by making a call to the authorization server's authorization endpoint, specifying the SSO token of the user.\n"
  },
  "response": [
    {
      "name": "Success - headers captured by HttpBin.",
      "originalRequest": {
        "method": "POST",
        "header": [
        ],
        "body": {
          "mode": "urlencoded",
          "urlencoded": [
            {
              "key": "scope",
              "value": "write ",
              "description": "Strings that are presented to the user for approval and included in tokens so that the protected resource may make decisions about what to give access to.",
              "type": "text"
            },
            {
              "key": "response_type",
              "value": "code",
              "description": "Response types the client will support and use.",
              "type": "text"
            },
            {
              "key": "client_id",
              "value": "{{postmanConfidentialClientId}}",
              "description": "The ID of the Confidential OAuth Client.",
              "type": "text"
            },
            {
              "key": "redirect_uri",
              "value": "{{redirect_uri}}",
              "description": "The complete URI to which client redirects the user if the request is successful.",
              "type": "text"
            },
            {
              "key": "decision",
              "value": "allow",
              "description": "The complete URI to which client redirects the user if the request is successful.",
              "type": "text"
            },
            {
              "key": "csrf",
              "value": "{{demoSSOToken}}",
              "description": "SSO token of the demo user, to protect against cross-site request forgery.",
              "type": "text"
            }
          ]
        },
        "url": {
          "raw": "{{amUrl}}/oauth2{{realm}}/authorize",
          "host": [
            "{{amUrl}}"
          ],
          "path": [
            "oauth2{{realm}}",
            "authorize"
          ]
        }
      },
      "status": "OK",
      "code": 200,
      "_postman_previewlanguage": "json",
      "header": [
        {
          "key": "Date",
          "value": "Thu, 13 Aug 2020 12:10:47 GMT"
        },
        {
          "key": "Content-Type",
          "value": "application/json"
        },
        {
          "key": "Content-Length",
          "value": "937"
        },
        {
          "key": "Connection",
          "value": "keep-alive"
        },
        {
          "key": "Server",
          "value": "gunicorn/19.9.0"
        },
        {
          "key": "Access-Control-Allow-Origin",
          "value": "*"
        },
        {
          "key": "Access-Control-Allow-Credentials",
          "value": "true"
        }
      ],
      "cookie": [
      ],
      "body": "{\n    \"args\": {\n        \"client_id\": \"forgerockDemoConfidentialClient\",\n        \"code\": \"oIQFFQ1S5Fxnqs5U_EMWxYEJktQ\",\n        \"iss\": \"http://openam.example.com:8080/openam/oauth2\"\n    },\n    \"data\": \"\",\n    \"files\": {},\n    \"form\": {},\n    \"headers\": {\n        \"Accept\": \"*/*\",\n        \"Accept-Encoding\": \"gzip, deflate, br\",\n        \"Cookie\": \"amlbcookie=01; iPlanetDirectoryPro=sOpI1RvbCgvlQk.*AAJTSQACMDEA.*\",\n        \"Host\": \"httpbin.org\",\n        \"Referer\": \"http://openam.example.com:8080/openam/oauth2/realms/root/authorize\",\n        \"User-Agent\": \"PostmanRuntime/7.26.3\",\n        \"X-Amzn-Trace-Id\": \"Root=1-5f352dc7-0d6bd5fceafcd01e856febd2\"\n    },\n    \"json\": null,\n    \"method\": \"GET\",\n    \"origin\": \"5.65.200.229\",\n    \"url\": \"https://httpbin.org/anything?code=oIQFFQ1S5Fxnqs5U_EMWxYEJktQ&iss=http:%2F%2Fopenam.example.com:8080%2Fopenam%2Foauth2&client_id=forgerockDemoConfidentialClient\"\n}"
    }
  ]
}