Chilkat Online Tools

PowerBuilder / ForgeRock Identity Cloud Collection / Step 2: Get Access Token

Back to Collection Items

integer li_rc
oleobject loo_Http
integer li_Success
oleobject loo_Req
oleobject loo_JsonParam1
oleobject loo_JsonParam5
oleobject loo_JsonParam6
oleobject loo_Resp

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

loo_Http = create oleobject
// Use "Chilkat_9_5_0.Http" for versions of Chilkat < 10.0.0
li_rc = loo_Http.ConnectToNewObject("Chilkat.Http")
if li_rc < 0 then
    destroy loo_Http
    MessageBox("Error","Connecting to COM object failed")
    return
end if

loo_Http.BasicAuth = 1
loo_Http.Login = "username"
loo_Http.Password = "password"

loo_Req = create oleobject
// Use "Chilkat_9_5_0.HttpRequest" for versions of Chilkat < 10.0.0
li_rc = loo_Req.ConnectToNewObject("Chilkat.HttpRequest")

loo_JsonParam1 = create oleobject
// Use "Chilkat_9_5_0.JsonObject" for versions of Chilkat < 10.0.0
li_rc = loo_JsonParam1.ConnectToNewObject("Chilkat.JsonObject")

loo_Req.AddParam("client_id",loo_JsonParam1.Emit())
loo_Req.AddParam("response_type","token")
loo_Req.AddParam("scope","write")
loo_Req.AddParam("decision","allow")

loo_JsonParam5 = create oleobject
// Use "Chilkat_9_5_0.JsonObject" for versions of Chilkat < 10.0.0
li_rc = loo_JsonParam5.ConnectToNewObject("Chilkat.JsonObject")

loo_Req.AddParam("csrf",loo_JsonParam5.Emit())

loo_JsonParam6 = create oleobject
// Use "Chilkat_9_5_0.JsonObject" for versions of Chilkat < 10.0.0
li_rc = loo_JsonParam6.ConnectToNewObject("Chilkat.JsonObject")

loo_Req.AddParam("redirect_uri",loo_JsonParam6.Emit())
loo_Req.AddParam("state","abc123")

loo_Resp = loo_Http.PostUrlEncoded("https://<tenant-name>.forgeblocks.com/am/oauth2/realms/root/realms/alpha/authorize",loo_Req)
if loo_Http.LastMethodSuccess = 0 then
    Write-Debug loo_Http.LastErrorText
    destroy loo_Http
    destroy loo_Req
    destroy loo_JsonParam1
    destroy loo_JsonParam5
    destroy loo_JsonParam6
    return
end if

Write-Debug string(loo_Resp.StatusCode)
Write-Debug loo_Resp.BodyStr
destroy loo_Resp


destroy loo_Http
destroy loo_Req
destroy loo_JsonParam1
destroy loo_JsonParam5
destroy loo_JsonParam6

Curl Command

curl -X POST
	-u 'username:password'
	-H "Content-Type: application/x-www-form-urlencoded"
	--data-urlencode 'client_id={{postmanPublicClientId}}'
	--data-urlencode 'response_type=token'
	--data-urlencode 'scope=write'
	--data-urlencode 'decision=allow'
	--data-urlencode 'csrf={{demoSSOToken}}'
	--data-urlencode 'redirect_uri={{redirect_uri}}'
	--data-urlencode 'state=abc123'
https://<tenant-name>.forgeblocks.com/am/oauth2/realms/root/realms/alpha/authorize

Postman Collection Item JSON

{
  "name": "Step 2: Get Access Token",
  "event": [
    {
      "listen": "test",
      "script": {
        "exec": [
          "function QueryStringToJSON(qs) {            ",
          "    var keyvaluepairs = qs.slice(qs.indexOf(\"#\")+1).split('&');",
          "    ",
          "    var result = {};",
          "    keyvaluepairs.forEach(function(keyvaluepair) {",
          "        keyvaluepair = keyvaluepair.split('=');",
          "        result[keyvaluepair[0]] = decodeURIComponent(keyvaluepair[1] || '');",
          "    });",
          "    return JSON.parse(JSON.stringify(result));",
          "}",
          "",
          "if(pm.response.code == 302)",
          "{",
          "   let redirectLocation = QueryStringToJSON(pm.response.headers.get(\"Location\"));",
          "    pm.globals.set(\"implicitGrantAccessToken\", redirectLocation.access_token);",
          "}",
          "else",
          "{",
          "    pm.globals.set(\"implicitGrantAccessToken\", \"ERROR: 302 not returned!\");",
          "}",
          "",
          "// TESTS",
          "",
          "pm.test(\"Follow redirects is NOT enabled in Postman (Status code is 302)\", () => {",
          "  // If response was 302, ensure Postman is following redirects.  ",
          "  pm.response.to.have.status(302);",
          "});",
          "",
          "pm.test(\"Response `Location` header contained `code` parameter\", () => {",
          "    let redirectLocation = QueryStringToJSON(pm.response.headers.get(\"Location\"));",
          "    pm.expect(redirectLocation.access_token).to.be.a(\"string\");",
          "});",
          ""
        ],
        "type": "text/javascript"
      }
    }
  ],
  "protocolProfileBehavior": {
    "followRedirects": false
  },
  "request": {
    "auth": {
      "type": "basic",
      "basic": [
        {
          "key": "password",
          "value": "{{postmanClientSecret}}",
          "type": "string"
        },
        {
          "key": "username",
          "value": "{{postmanPublicClientId}}",
          "type": "string"
        }
      ]
    },
    "method": "POST",
    "header": [
      {
        "key": "Content-Type",
        "name": "Content-Type",
        "value": "application/x-www-form-urlencoded",
        "type": "text"
      }
    ],
    "body": {
      "mode": "urlencoded",
      "urlencoded": [
        {
          "key": "client_id",
          "value": "{{postmanPublicClientId}}",
          "description": "The ID of the Public OAuth Client.",
          "type": "text"
        },
        {
          "key": "response_type",
          "value": "token",
          "description": "Response types the client will support and use.",
          "type": "text"
        },
        {
          "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": "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": "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": "state",
          "value": "abc123",
          "type": "text"
        }
      ]
    },
    "url": {
      "raw": "{{amUrl}}/oauth2{{realm}}/authorize",
      "host": [
        "{{amUrl}}"
      ],
      "path": [
        "oauth2{{realm}}",
        "authorize"
      ]
    }
  },
  "response": [
    {
      "name": "Example - Location header contains access_token.",
      "originalRequest": {
        "method": "POST",
        "header": [
          {
            "key": "Content-Type",
            "name": "Content-Type",
            "value": "application/x-www-form-urlencoded",
            "type": "text"
          }
        ],
        "body": {
          "mode": "urlencoded",
          "urlencoded": [
            {
              "key": "client_id",
              "value": "{{postmanPublicClientId}}",
              "description": "The ID of the Public OAuth Client.",
              "type": "text"
            },
            {
              "key": "response_type",
              "value": "token",
              "description": "Response types the client will support and use.",
              "type": "text"
            },
            {
              "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": "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": "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"
            }
          ]
        },
        "url": {
          "raw": "{{amUrl}}/oauth2{{realm}}/authorize",
          "host": [
            "{{amUrl}}"
          ],
          "path": [
            "oauth2{{realm}}",
            "authorize"
          ]
        }
      },
      "status": "Found",
      "code": 302,
      "_postman_previewlanguage": "plain",
      "header": [
        {
          "key": "X-Frame-Options",
          "value": "SAMEORIGIN"
        },
        {
          "key": "X-Content-Type-Options",
          "value": "nosniff"
        },
        {
          "key": "Cache-Control",
          "value": "no-store"
        },
        {
          "key": "Location",
          "value": "https://httpbin.org/anything#access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkZW1vIiwiY3RzIjoiT0FVVEgyX1NUQVRFTEVTU19HUkFOVCIsImF1dGhfbGV2ZWwiOjAsImF1ZGl0VHJhY2tpbmdJZCI6IjAzN2YwMmY5LWQ4MjEtNGY3Mi04NTYzLWM1MDUwYzQwZmRjMy01MTM5OSIsImlzcyI6Imh0dHA6Ly9vcGVuYW0uZXhhbXBsZS5jb206ODA4MC9vcGVuYW0vb2F1dGgyIiwidG9rZW5OYW1lIjoiYWNjZXNzX3Rva2VuIiwidG9rZW5fdHlwZSI6IkJlYXJlciIsImF1dGhHcmFudElkIjoiNi1uLU1GLWRLMGJfTng2TnFFQVFCdkVYQ2xzIiwiYXVkIjoiZm9yZ2Vyb2NrRGVtb1B1YmxpY0NsaWVudCIsIm5iZiI6MTU5NzMyMDkxOCwiZ3JhbnRfdHlwZSI6InRva2VuIiwic2NvcGUiOlsid3JpdGUiXSwiYXV0aF90aW1lIjoxNTk3MzIwOTAxLCJyZWFsbSI6Ii8iLCJleHAiOjE1OTczMjQ1MTgsImlhdCI6MTU5NzMyMDkxOCwiZXhwaXJlc19pbiI6MzYwMCwianRpIjoiMlJLWUx2U0IyNUVoVFE3WHhITzBXVFZqa25VIn0.SdLW4L8iZLiTymoL_SJCaGHQ5GmBuYlelcKe-Ou9gwM&iss=http://openam.example.com:8080/openam/oauth2&token_type=Bearer&expires_in=3599&client_id=forgerockDemoPublicClient"
        },
        {
          "key": "Pragma",
          "value": "no-cache"
        },
        {
          "key": "Set-Cookie",
          "value": "OAUTH_REQUEST_ATTRIBUTES=DELETED; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/; Domain=example.com; HttpOnly"
        },
        {
          "key": "Content-Length",
          "value": "0"
        },
        {
          "key": "Date",
          "value": "Thu, 13 Aug 2020 12:15:18 GMT"
        }
      ],
      "cookie": [
      ],
      "body": ""
    }
  ]
}