Chilkat Online Tools

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

Back to Collection Items

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

$oHttp = ObjCreate("Chilkat_9_5_0.Http")
Local $bSuccess

$oReq = ObjCreate("Chilkat_9_5_0.HttpRequest")
$oReq.AddParam "scope","share"
$oReq.AddParam "response_type","code"

$oJsonParam3 = ObjCreate("Chilkat_9_5_0.JsonObject")
$oReq.AddParam "client_id",$oJsonParam3.Emit()

$oJsonParam4 = ObjCreate("Chilkat_9_5_0.JsonObject")
$oReq.AddParam "csrf",$oJsonParam4.Emit()

$oJsonParam5 = ObjCreate("Chilkat_9_5_0.JsonObject")
$oReq.AddParam "redirect_uri",$oJsonParam5.Emit()
$oReq.AddParam "decision","allow"

$oJsonParam7 = ObjCreate("Chilkat_9_5_0.JsonObject")
$oReq.AddParam "code_challenge",$oJsonParam7.Emit()
$oReq.AddParam "code_challenge_method","S256"

$oReq.AddHeader "Authorization","Bearer <access_token>"
$oReq.AddHeader "Cookie","{{cookieName}}={{demoSSOToken}}"

Local $oResp = $oHttp.PostUrlEncoded("https://<tenant-name>.forgeblocks.com/am/oauth2/realms/root/realms/alpha/authorize",$oReq)
If ($oHttp.LastMethodSuccess = False) Then
    ConsoleWrite($oHttp.LastErrorText & @CRLF)
    Exit
EndIf

$oSbResponseBody = ObjCreate("Chilkat_9_5_0.StringBuilder")
$oResp.GetBodySb($oSbResponseBody)

$oJResp = ObjCreate("Chilkat_9_5_0.JsonObject")
$oJResp.LoadSb($oSbResponseBody)
$oJResp.EmitCompact = False

ConsoleWrite("Response Body:" & @CRLF)
ConsoleWrite($oJResp.Emit() & @CRLF)

Local $iRespStatusCode = $oResp.StatusCode
ConsoleWrite("Response Status Code = " & $iRespStatusCode & @CRLF)
If ($iRespStatusCode >= 400) Then
    ConsoleWrite("Response Header:" & @CRLF)
    ConsoleWrite($oResp.Header & @CRLF)
    ConsoleWrite("Failed." & @CRLF)

    Exit
EndIf

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

; {
;   "args": {
;     "client_id": "forgerockDemoConfidentialClient",
;     "code": "rXspXy1Z03nredTwVDo6qCO1I-4",
;     "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",
;     "Iplanetdirectorypro": "sOpI1RvbCgvlQk.*AAJTSQACMDEA.*",
;     "Referer": "http://openam.example.com:8080/openam/oauth2/realms/root/authorize",
;     "User-Agent": "PostmanRuntime/7.26.3",
;     "X-Amzn-Trace-Id": "Root=1-5f352e89-db9fc460f6fadf84ef688bbc"
;   },
;   "json": null,
;   "method": "GET",
;   "origin": "5.65.200.229",
;   "url": "https://httpbin.org/anything?code=rXspXy1Z03nredTwVDo6qCO1I-4&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

Local $sClient_id = $oJResp.StringOf("args.client_id")
Local $sCode = $oJResp.StringOf("args.code")
Local $sIss = $oJResp.StringOf("args.iss")
Local $sData = $oJResp.StringOf("data")
Local $sAccept = $oJResp.StringOf("headers.Accept")
Local $sAccept_Encoding = $oJResp.StringOf("headers.Accept-Encoding")
Local $sCookie = $oJResp.StringOf("headers.Cookie")
Local $sHost = $oJResp.StringOf("headers.Host")
Local $sIplanetdirectorypro = $oJResp.StringOf("headers.Iplanetdirectorypro")
Local $sReferer = $oJResp.StringOf("headers.Referer")
Local $sUser_Agent = $oJResp.StringOf("headers.User-Agent")
Local $sX_Amzn_Trace_Id = $oJResp.StringOf("headers.X-Amzn-Trace-Id")
Local $sJson = $oJResp.StringOf("json")
Local $sMethod = $oJResp.StringOf("method")
Local $sOrigin = $oJResp.StringOf("origin")
Local $sUrl = $oJResp.StringOf("url")

Curl Command

curl -X POST
	-H "Authorization: Bearer <access_token>"
	-H "Cookie: {{cookieName}}={{demoSSOToken}}"
	--data-urlencode 'scope=share'
	--data-urlencode 'response_type=code'
	--data-urlencode 'client_id={{postmanConfidentialClientId}}'
	--data-urlencode 'csrf={{demoSSOToken}}'
	--data-urlencode 'redirect_uri={{redirect_uri}}'
	--data-urlencode 'decision=allow'
	--data-urlencode 'code_challenge={{code_challenge}}'
	--data-urlencode 'code_challenge_method=S256'
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": [
          "var jsonData = JSON.parse(responseBody);",
          "",
          "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"
      }
    },
    {
      "listen": "prerequest",
      "script": {
        "exec": [
          "function base64URLEncode(words) {",
          "   return CryptoJS.enc.Base64.stringify(words)",
          "   .replace(/\\+/g, '-')",
          "   .replace(/\\//g, '_')",
          "   .replace(/=/g, '');",
          "}",
          "const code_verifier = base64URLEncode(CryptoJS.lib.WordArray.random(50));",
          "const code_challenge = base64URLEncode(CryptoJS.SHA256(code_verifier));",
          "",
          "pm.globals.set(\"code_challenge\", code_challenge);",
          "pm.globals.set(\"code_verifier\", code_verifier);"
        ],
        "type": "text/javascript"
      }
    }
  ],
  "request": {
    "method": "POST",
    "header": [
      {
        "key": "Cookie",
        "value": "{{cookieName}}={{demoSSOToken}}",
        "type": "text"
      }
    ],
    "body": {
      "mode": "urlencoded",
      "urlencoded": [
        {
          "key": "scope",
          "value": "share",
          "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": "csrf",
          "value": "{{demoSSOToken}}",
          "description": "SSO token of a ForgeRock user, to protect against cross-site request forgery.",
          "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": "Decision that grants access to the authentication code. When using a browser, the user would consent that the client can access their information. This flow can be used machine-to-machine, by assuming consent, for example between two services provided by the same organization.",
          "type": "text"
        },
        {
          "key": "code_challenge",
          "value": "{{code_challenge}}",
          "description": "The generated code challenge. See the \"Pre-request SCript\" tab for details.",
          "type": "text"
        },
        {
          "key": "code_challenge_method",
          "value": "S256",
          "description": "The method used to generate the code challenge.",
          "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."
  },
  "response": [
    {
      "name": "Example",
      "originalRequest": {
        "method": "POST",
        "header": [
          {
            "key": "iplanetDirectoryPro",
            "value": "{{demoSSOToken}}",
            "type": "text"
          }
        ],
        "body": {
          "mode": "urlencoded",
          "urlencoded": [
            {
              "key": "scope",
              "value": "share",
              "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": "csrf",
              "value": "{{demoSSOToken}}",
              "description": "SSO token of a ForgeRock user, to protect against cross-site request forgery.",
              "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": "Decision that grants access to the authentication code. When using a browser, the user would consent that the client can access their information. This flow can be used machine-to-machine, by assuming consent, for example between two services provided by the same organization.",
              "type": "text"
            },
            {
              "key": "code_challenge",
              "value": "{{code_challenge}}",
              "description": "The generated code challenge.",
              "type": "text"
            },
            {
              "key": "code_challenge_method",
              "value": "S256",
              "description": "The method used to generate the code challenge.",
              "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:14:01 GMT"
        },
        {
          "key": "Content-Type",
          "value": "application/json"
        },
        {
          "key": "Content-Length",
          "value": "1079"
        },
        {
          "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\": \"rXspXy1Z03nredTwVDo6qCO1I-4\",\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        \"Iplanetdirectorypro\": \"sOpI1RvbCgvlQk.*AAJTSQACMDEA.*\",\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-5f352e89-db9fc460f6fadf84ef688bbc\"\n    },\n    \"json\": null,\n    \"method\": \"GET\",\n    \"origin\": \"5.65.200.229\",\n    \"url\": \"https://httpbin.org/anything?code=rXspXy1Z03nredTwVDo6qCO1I-4&iss=http:%2F%2Fopenam.example.com:8080%2Fopenam%2Foauth2&client_id=forgerockDemoConfidentialClient\"\n}"
    }
  ]
}