Chilkat Online Tools

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

Back to Collection Items

// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

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

    CkHttp http = new CkHttp();
    boolean success;

    http.put_BasicAuth(true);
    http.put_Login("username");
    http.put_Password("password");

    CkHttpRequest req = new CkHttpRequest();

    CkJsonObject jsonParam1 = new CkJsonObject();
    req.AddParam("client_id",jsonParam1.emit());
    req.AddParam("response_type","token");
    req.AddParam("scope","write");
    req.AddParam("decision","allow");

    CkJsonObject jsonParam5 = new CkJsonObject();
    req.AddParam("csrf",jsonParam5.emit());

    CkJsonObject jsonParam6 = new CkJsonObject();
    req.AddParam("redirect_uri",jsonParam6.emit());
    req.AddParam("state","abc123");

    CkHttpResponse resp = http.PostUrlEncoded("https://<tenant-name>.forgeblocks.com/am/oauth2/realms/root/realms/alpha/authorize",req);
    if (http.get_LastMethodSuccess() == false) {
        Log.i(TAG, http.lastErrorText());
        return;
        }

    Log.i(TAG, String.valueOf(resp.get_StatusCode()));
    Log.i(TAG, resp.bodyStr());


  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}

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": ""
    }
  ]
}