

# Step 2: Create a Salesforce integration user and External Client App

In this step, a Salesforce administrator creates an integration user that only this integration uses, gives it access, and creates an External Client App that runs as that user. Every call the gateway makes runs as the app's **Run As** user, so the integration user's name in **Created By** and **Last Modified By** identifies the integration's changes.

The setup script grants the integration user these permissions by default:
+ Read, create and edit on Case, Account and Contact, with read on every field of the three objects and edit on every field that can be edited. Your Salesforce administrator decides which fields the integration user can read and edit.
+ Delete on Case, which lets a guide you build delete cases with `deleteCase`.
+ Run Flows, which lets guides and flow modules you build start active autolaunched Salesforce flows with `runFlow`. The sample guide starts no Salesforce flow.
+ API Enabled and API Only User: the user calls the Salesforce APIs and can't sign in to the Salesforce user interface.
+ Access Activities, which the setup script grants and checks.

Your Salesforce administrator chooses the user's profile, its license and any permission set license. Record access comes from your org's sharing settings, so make sure that the integration user can see the accounts, contacts and cases that agents work with.

## Create the integration user and its access
<a name="real-time-data-integration-credentials-salesforce"></a>

For the Developer Console or the CLI, the setup script is anonymous Apex, which you run once without saving it in your org. It runs as you and needs the **Author Apex** permission. At the top of the script, change `username` and `email`, and leave `profileName` empty. For `email`, use an address your team reads, such as a team alias; nothing in this setup is sent to it. For its other values and what each line it prints means, see [What the setup script does and prints](real-time-data-integration-troubleshoot.md#real-time-data-integration-troubleshoot-script).

### The setup script
<a name="real-time-data-integration-credentials-script"></a>

```
// Real-time data integration with Agent workspace: creates the integration user and grants the access the
// integration needs, then prints PASS or FAIL for each permission it grants. Run it in the Developer Console (Debug,
// Open Execute Anonymous Window, with Debug Only selected in the log) or with sf apex run.
// It changes nothing unless every step succeeds, and it is safe to run again.

// ---- Your values ----
String username = 'connect-integration@yourcompany.com';   // the integration user's username, unique across all Salesforce orgs
String email = 'admin@yourcompany.com';                   // where Salesforce sends this user's notices; no welcome email is sent
String lastName = 'Integration User';
String profileName = '';                                  // the new user's profile; leave empty to list your org's profiles
String permissionSetLicense = '';                         // optional: a permission set license to assign to the user
String psName = 'Connect_Real_Time_Data_Integration';     // the permission set; use another name for a second stack
Boolean reuseExistingUser = false;                        // true only to give this access to a user that already exists
// Object access: 'read', 'create', 'edit', 'delete'. Add your custom objects here, for example 'Order__c' => 'read,edit',
// and the Platform Events guides publish, for example 'Order_Event__e' => 'read,create'.
Map<String, String> objects = new Map<String, String>{
    'Case' => 'read,create,edit,delete',
    'Account' => 'read,create,edit',
    'Contact' => 'read,create,edit'
};
Boolean runFlows = true;                                  // lets guides start autolaunched flows
// The invocable Apex classes guides call with runApexAction, for example 'OrderRefund'. The script adds access to
// these classes; it doesn't remove access to a class you take off this list.
List<String> apexClasses = new List<String>{};
// ---- End of your values ----

// Every line the script prints starts with LDI.
void say(String line) { System.debug(LoggingLevel.ERROR, 'LDI' + ' ' + line); }

void listProfiles() {
    Map<Id, UserLicense> licenses = new Map<Id, UserLicense>([SELECT Id, Name, TotalLicenses, UsedLicenses FROM UserLicense WHERE Status = 'Active']);
    say('Profiles in this org, with each one\'s user license and how many of that license are available:');
    for (Profile p : [SELECT Name, UserLicenseId FROM Profile WHERE UserType = 'Standard' ORDER BY Name]) {
        UserLicense l = licenses.get(p.UserLicenseId);
        if (l != null) say('  ' + p.Name + ', license ' + l.Name + ', ' + (l.TotalLicenses - l.UsedLicenses) + ' available');
    }
    say('STOPPED: nothing was changed. Set profileName to the profile you chose for the integration user, exactly as listed, and run the script again.');
}

void listPermissionSetLicenses() {
    say('Permission set licenses in this org, with how many are available:');
    for (PermissionSetLicense l : [SELECT MasterLabel, TotalLicenses, UsedLicenses FROM PermissionSetLicense WHERE Status = 'Active' ORDER BY MasterLabel]) {
        say('  ' + l.MasterLabel + ', ' + (l.TotalLicenses - l.UsedLicenses) + ' available');
    }
}

Boolean isLicenseError(String message) {
    String m = message.toLowerCase();
    return m.contains('license doesn\'t allow') || m.contains('license does not allow');
}

if (username.contains('yourcompany.com') || email.contains('yourcompany.com')) {
    say('STOPPED: nothing was changed. Set username and email at the top of the script to your own values, and run it again.');
    return;
}

// Progress lines print only after every change succeeded, so a stopped run shows only why it stopped.
List<String> progress = new List<String>();
// The objects, by their API names as Salesforce spells them.
Map<String, String> access = new Map<String, String>();
Savepoint sp = Database.setSavepoint();
User u;
try {
    // 1. The user: reuse it if it exists, otherwise create it on profileName.
    Map<String, Schema.SObjectType> types = Schema.getGlobalDescribe();
    for (String name : objects.keySet()) {
        Schema.SObjectType t = types.get(name);
        if (t == null) { throw new IllegalArgumentException('No object named ' + name + ' in this org. Check the objects list.'); }
        access.put(t.getDescribe().getName(), objects.get(name));
    }
    List<User> existing = [SELECT Id, IsActive, Profile.Name FROM User WHERE Username = :username];
    if (!existing.isEmpty()) {
        u = existing[0];
        if (u.Id == UserInfo.getUserId()) {
            say('STOPPED: nothing was changed. ' + username + ' is your own user; enter a new username for the integration user.');
            return;
        }
        Boolean holdsSet = [SELECT COUNT() FROM PermissionSetAssignment WHERE AssigneeId = :u.Id AND PermissionSet.Name = :psName] > 0;
        if (!reuseExistingUser && (!holdsSet || !u.IsActive)) {
            say('STOPPED: nothing was changed. A user named ' + username + ' already exists' + (u.IsActive ? '' : ' and is inactive')
                + '. To create a new integration user, enter a new username. To give this access to that user, which makes it an API-only user'
                + (u.IsActive ? '' : ' and activates it') + ', set reuseExistingUser to true and run the script again.');
            return;
        }
        progress.add('User ' + username + ' exists, on profile ' + u.Profile.Name + '; its profile is not changed.');
        if (!u.IsActive) { u.IsActive = true; update u; progress.add('User ' + username + ' was inactive and is now active.'); }
    } else {
        List<Profile> profiles = String.isBlank(profileName) ? new List<Profile>() : [SELECT Id FROM Profile WHERE Name = :profileName];
        if (profiles.isEmpty()) {
            if (!String.isBlank(profileName)) say('No profile named "' + profileName + '" in this org.');
            listProfiles();
            return;
        }
        u = new User(Username = username, Email = email, LastName = lastName,
            Alias = 'connint', ProfileId = profiles[0].Id, TimeZoneSidKey = UserInfo.getTimeZone().getID(),
            LocaleSidKey = UserInfo.getLocale(), LanguageLocaleKey = UserInfo.getLanguage(), EmailEncodingKey = 'UTF-8');
        Database.DMLOptions noEmail = new Database.DMLOptions();
        noEmail.EmailHeader.triggerUserEmail = false;
        noEmail.optAllOrNone = true;   // fail on any error instead of returning it unchecked
        Database.insert(u, noEmail);
        progress.add('Created user ' + username + ' on profile ' + profileName + '. No welcome email was sent.');
    }

    // 2. The permission set license, if one was given.
    if (!String.isBlank(permissionSetLicense)) {
        List<PermissionSetLicense> psl = [SELECT Id FROM PermissionSetLicense WHERE MasterLabel = :permissionSetLicense OR DeveloperName = :permissionSetLicense];
        if (psl.isEmpty()) {
            Database.rollback(sp);
            say('No permission set license named "' + permissionSetLicense + '" in this org.');
            listPermissionSetLicenses();
            say('STOPPED: nothing was changed. Set permissionSetLicense to one of these names, or leave it empty, and run the script again.');
            return;
        }
        if ([SELECT COUNT() FROM PermissionSetLicenseAssign WHERE AssigneeId = :u.Id AND PermissionSetLicenseId = :psl[0].Id] == 0) {
            insert new PermissionSetLicenseAssign(AssigneeId = u.Id, PermissionSetLicenseId = psl[0].Id);
            progress.add('Assigned the permission set license ' + permissionSetLicense + '.');
        } else {
            progress.add('The user already has the permission set license ' + permissionSetLicense + '.');
        }
    }

    // 3. The permission set: create or update it, and replace its object and field access.
    List<PermissionSet> found = [SELECT Id FROM PermissionSet WHERE Name = :psName];
    if (!found.isEmpty() && [SELECT COUNT() FROM PermissionSetAssignment WHERE PermissionSetId = :found[0].Id AND AssigneeId != :u.Id] > 0) {
        Database.rollback(sp);
        say('STOPPED: nothing was changed. Permission set ' + psName + ' is assigned to other users; set psName to a new name.');
        return;
    }
    PermissionSet ps = found.isEmpty() ? new PermissionSet(Name = psName, Label = psName.replace('_', ' ')) : found[0];
    ps.PermissionsApiEnabled = true;
    ps.PermissionsApiUserOnly = true;
    ps.PermissionsActivitiesAccess = true;  // Access Activities
    ps.PermissionsRunFlow = runFlows;
    upsert ps;

    delete [SELECT Id FROM FieldPermissions WHERE ParentId = :ps.Id];
    delete [SELECT Id FROM ObjectPermissions WHERE ParentId = :ps.Id];
    List<ObjectPermissions> objectPerms = new List<ObjectPermissions>();
    List<FieldPermissions> fieldPerms = new List<FieldPermissions>();
    for (String name : access.keySet()) {
        Set<String> ops = new Set<String>(access.get(name).replace(' ', '').split(','));
        Schema.SObjectType t = types.get(name);
        Boolean edit = ops.contains('edit');
        objectPerms.add(new ObjectPermissions(ParentId = ps.Id, SobjectType = name,
            PermissionsRead = true, PermissionsCreate = ops.contains('create'),
            PermissionsEdit = edit || ops.contains('delete'), PermissionsDelete = ops.contains('delete')));
        for (Schema.SObjectField f : t.getDescribe().fields.getMap().values()) {
            Schema.DescribeFieldResult d = f.getDescribe();
            if (!d.isPermissionable()) continue;   // required and system fields: access comes with the object
            if (d.getCompoundFieldName() != null) continue;   // address parts: access comes with BillingAddress and the like
            fieldPerms.add(new FieldPermissions(ParentId = ps.Id, SobjectType = name, Field = name + '.' + d.getName(),
                // Compound fields such as BillingAddress report not updateable; their parts are, so follow the object.
                PermissionsRead = true, PermissionsEdit = edit && !d.isCalculated()
                    && (d.isUpdateable() || d.getType() == Schema.DisplayType.ADDRESS)));
        }
    }
    insert objectPerms;
    insert fieldPerms;

    Set<Id> granted = new Set<Id>();
    for (SetupEntityAccess a : [SELECT SetupEntityId FROM SetupEntityAccess WHERE ParentId = :ps.Id]) granted.add(a.SetupEntityId);
    List<SetupEntityAccess> classAccess = new List<SetupEntityAccess>();
    List<ApexClass> classes = [SELECT Id, Name FROM ApexClass WHERE Name IN :apexClasses AND NamespacePrefix = null];
    if (classes.size() != new Set<String>(apexClasses).size()) {
        throw new IllegalArgumentException('Not every class in apexClasses exists in this org: ' + apexClasses);
    }
    for (ApexClass c : classes) {
        if (!granted.contains(c.Id)) classAccess.add(new SetupEntityAccess(ParentId = ps.Id, SetupEntityId = c.Id));
    }
    insert classAccess;

    // 4. Assign the permission set.
    if ([SELECT COUNT() FROM PermissionSetAssignment WHERE AssigneeId = :u.Id AND PermissionSetId = :ps.Id] == 0) {
        insert new PermissionSetAssignment(AssigneeId = u.Id, PermissionSetId = ps.Id);
    }
    progress.add('Permission set ' + psName + ': ' + objectPerms.size() + ' objects, ' + fieldPerms.size() + ' fields, '
        + classes.size() + ' Apex classes, assigned to ' + username + '.');
    for (String line : progress) say(line);
} catch (Exception e) {
    Database.rollback(sp);
    String message = e.getMessage();
    if (isLicenseError(message) && String.isBlank(permissionSetLicense)) {
        say('Salesforce refused this access for the user\'s license: ' + message);
        listPermissionSetLicenses();
        say('STOPPED: nothing was changed. The user\'s license can\'t grant every permission the integration user needs: API Enabled, '
            + 'API Only User, Access Activities' + (runFlows ? ', Run Flows' : '') + ', and the object access in objects ('
            + String.join(new List<String>(objects.keySet()), ', ') + '). Which license and permission set license the user has is your '
            + 'organization\'s decision. Choose a profile whose user license allows these permissions, or set permissionSetLicense to a '
            + 'permission set license that adds them, and run the script again.');
    } else if (message.contains('LICENSE_LIMIT_EXCEEDED') || message.toLowerCase().contains('license limit exceeded')) {
        say('Salesforce refused to create the user: the profile\'s user license has none available.');
        listProfiles();
    } else if (message.contains('DUPLICATE_USERNAME') || message.toLowerCase().contains('duplicate username')) {
        say('STOPPED: nothing was changed. The username ' + username + ' is already used in another Salesforce org. Choose another username.');
    } else {
        say('STOPPED: nothing was changed. Salesforce returned: ' + message);
    }
    return;
}

// 5. Read back what the user can do, across every permission set it holds, including its profile's.
Set<Id> sets = new Set<Id>();
for (PermissionSetAssignment a : [SELECT PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId = :u.Id]) sets.add(a.PermissionSetId);
Map<String, Set<String>> held = new Map<String, Set<String>>();
for (ObjectPermissions p : [SELECT SobjectType, PermissionsRead, PermissionsCreate, PermissionsEdit, PermissionsDelete
        FROM ObjectPermissions WHERE ParentId IN :sets AND SobjectType IN :access.keySet()]) {
    if (!held.containsKey(p.SobjectType)) held.put(p.SobjectType, new Set<String>());
    if (p.PermissionsRead) held.get(p.SobjectType).add('read');
    if (p.PermissionsCreate) held.get(p.SobjectType).add('create');
    if (p.PermissionsEdit) held.get(p.SobjectType).add('edit');
    if (p.PermissionsDelete) held.get(p.SobjectType).add('delete');
}
Boolean allPass = true;
for (String name : access.keySet()) {
    for (String op : access.get(name).replace(' ', '').split(',')) {
        Boolean ok = held.containsKey(name) && held.get(name).contains(op);
        allPass &= ok;
        say((ok ? 'PASS ' : 'FAIL ') + name + ' ' + op);
    }
}
Boolean api = false, apiOnly = false, flows = false, activities = false;
for (PermissionSet p : [SELECT PermissionsApiEnabled, PermissionsApiUserOnly, PermissionsRunFlow, PermissionsActivitiesAccess FROM PermissionSet WHERE Id IN :sets]) {
    api |= p.PermissionsApiEnabled; apiOnly |= p.PermissionsApiUserOnly; flows |= p.PermissionsRunFlow; activities |= p.PermissionsActivitiesAccess;
}
say((api ? 'PASS ' : 'FAIL ') + 'API Enabled'); allPass &= api;
say((apiOnly ? 'PASS ' : 'FAIL ') + 'API Only User'); allPass &= apiOnly;
say((activities ? 'PASS ' : 'FAIL ') + 'Access Activities' + (activities ? '' : ': give the user a profile that has Access Activities')); allPass &= activities;
if (runFlows) { say((flows ? 'PASS ' : 'FAIL ') + 'Run Flows'); allPass &= flows; }
if (allPass) {
    say('DONE: every permission passed. Use ' + username + ' as the External Client App\'s Run As user.');
} else {
    say('DONE WITH FAILURES: give the user the access marked FAIL, then run the script again.');
}
```

Create the user and its access in one of these ways:

------
#### [ Developer Console (recommended) ]

1. In Salesforce, choose the gear icon, then **Developer Console**. It opens in a new window.

1. Choose **Debug**, **Open Execute Anonymous Window**, delete any code in the window, paste the script, and at the top change `username` and `email`. Leave `profileName` empty.

1. Select **Open Log**, and choose **Execute**. The log opens in a tab. Select **Debug Only** at the bottom of the log, so it shows only the script's lines, which start with `LDI`.

1. The first run lists your org's profiles and stops. Enter the profile your Salesforce administrator chose, whose license has at least one available, in `profileName`, and choose **Execute** again.

The user is ready when the last line is `DONE: every permission passed`.

------
#### [ Salesforce CLI ]

1. On your own computer, in bash (on macOS, type **bash** first), with the [Salesforce CLI](https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_install_cli.htm) installed, sign in to your org as a System Administrator. The block asks for your My Domain URL, from Setup, **My Domain**:

   ```
   (
     printf 'My Domain URL, for example https://mycompany.my.salesforce.com: '; read -r SF_DOMAIN
     SF_DOMAIN=${SF_DOMAIN%/}
     case "$SF_DOMAIN" in https://*.my.salesforce.com) ;; *) echo "\"$SF_DOMAIN\" isn't a My Domain URL. Copy it from Setup, My Domain, including https://."; exit 1 ;; esac
     sf org login web --instance-url "$SF_DOMAIN" --alias connect-org --set-default
   )
   ```

   A browser opens for you to sign in. The command prints `Successfully authorized`.

1. Save the script, with your values, as `integration-user-permissions.apex` in the folder where you run the CLI, and run it. The block saves the CLI's output in `integration-user-permissions.log` and prints only the script's lines, or Salesforce's error if the script printed none:

   ```
   (
     sf apex run --file integration-user-permissions.apex > integration-user-permissions.log 2>&1
     if grep -q 'LDI ' integration-user-permissions.log; then
       grep -o 'LDI .*' integration-user-permissions.log
     else
       echo "The script printed no LDI lines. Salesforce reported:"
       grep -v '^Execute Anonymous:' integration-user-permissions.log | grep -iE -A2 'error|exception' | head -20
     fi
   )
   ```

1. The first run lists your org's profiles and stops. Enter the profile you chose, on a license that has at least one available, in `profileName`, save the file, and run the command again.

The user is ready when the last line is `DONE: every permission passed`.

------
#### [ Setup by hand (no Apex) ]

Use Setup only if your org doesn't let you run anonymous Apex. These procedures create the same user and permission set as the script, but don't print PASS or FAIL.

**To create the integration user in Setup**

1. In **Setup**, open **Users**, and choose **New User**.

1. Choose the **User License** and the **Profile** you chose for the integration user.

1. Enter a last name, an email and a username, clear **Generate new password and notify user immediately**, and choose **Save**.

**To grant access in Setup**

1. In **Setup**, open **Permission Sets**, and choose **New**.

1. Enter the label **Connect real-time data integration** and the API name **Connect\_Real\_Time\_Data\_Integration**, the name the script uses (if another stack already uses that permission set, choose another name), leave **License** as **--None--**, and choose **Save**.

1. Choose **System Permissions**, **Edit**, select **API Enabled**, **API Only User**, **Run Flows** and **Access Activities**, and choose **Save**.

1. Choose **Object Settings**, **Cases**, **Edit**. Select **Read**, **Create**, **Edit** and **Delete**, select **Read Access** and **Edit Access** for every field, and choose **Save**.

1. Do the same for **Accounts** and **Contacts**, with **Read**, **Create** and **Edit**, and no **Delete**.

1. Do the same for each custom object your guides use, with the access they need, and with **Read** and **Create** for each Platform Event they publish.

1. If guides call invocable Apex with `runApexAction`, choose **Apex Class Access**, **Edit**, add those classes, and choose **Save**.

1. Choose **Manage Assignments**, **Add Assignment**, select the integration user, and choose **Assign**. If this fails with `The user license doesn't allow the permission`, see [Salesforce user and access](real-time-data-integration-troubleshoot.md#real-time-data-integration-troubleshoot-user).

The user is ready when the permission set's **Assigned Users** lists the integration user.

------

If the script ends with any other line, see [What the setup script does and prints](real-time-data-integration-troubleshoot.md#real-time-data-integration-troubleshoot-script).

## Create the External Client App
<a name="real-time-data-integration-credentials-app"></a>

**To create the External Client App in Setup**

1. In **Setup**, open **External Client App Manager**, and choose **New External Client App**.

1. Enter a name with no hyphens, for example **Connect Integration**, and a contact email.

1. Under **API (Enable OAuth Settings)**, select **Enable OAuth**, and enter any valid callback URL, for example `https://localhost/callback`.

1. Add the **Manage user data via APIs (api)** scope, select **Enable Client Credentials Flow**, choose **OK** in the confirmation, and choose **Create**.

1. On the app's **Policies** tab, choose **Edit**, expand **OAuth Policies**, and under **OAuth Flows and External Client App Enhancements**, select **Enable Client Credentials Flow** again. In **Run As (Username)**, enter the integration user's username, and choose **Save**.

1. On the app's **Settings** tab, under **OAuth Settings**, **App Settings**, choose **Consumer Key and Secret**. It opens a new tab, after Salesforce emails you a verification code. Copy the consumer key and the consumer secret.

1. In **Setup**, open **My Domain**, and copy your My Domain URL.

## Check that the app issues tokens as the integration user
<a name="real-time-data-integration-credentials-check"></a>

Expand the token check script, copy it, paste it at the prompt, and press Enter. It asks for the My Domain URL, the consumer key and the consumer secret, and prints the user the app runs as.

### The token check script
<a name="real-time-data-integration-code-token-check-script"></a>

```
(
  umask 077; D=$(mktemp -d); trap 'rm -rf "$D"' EXIT
  printf 'My Domain URL, for example https://mycompany.my.salesforce.com: '; read -r SF_DOMAIN
  SF_DOMAIN=${SF_DOMAIN%/}
  case "$SF_DOMAIN" in https://*.my.salesforce.com) ;; *) echo "NO TOKEN: \"$SF_DOMAIN\" isn't a My Domain URL. Copy it from Setup, My Domain, including https://."; exit 1 ;; esac
  printf 'Consumer key: '; read -r SF_KEY
  printf 'Consumer secret (input hidden: paste and press Enter): '; read -rs SF_SECRET; echo
  printf '%s' "$SF_SECRET" > "$D/secret"; unset SF_SECRET
  curl -sS -o "$D/token.json" -X POST "$SF_DOMAIN/services/oauth2/token" \
    -d grant_type=client_credentials --data-urlencode "client_id=$SF_KEY" \
    --data-urlencode "client_secret@$D/secret" 2> "$D/curl.err" \
    || { echo "NO TOKEN: couldn't reach $SF_DOMAIN: $(cat "$D/curl.err")"; echo "  Check the My Domain URL."; exit 1; }
  python3 -I - "$D" <<'PY' || exit 1
import json, sys
d = sys.argv[1]
try:
    r = json.load(open(d + "/token.json"))
except ValueError:
    print("NO TOKEN: Salesforce didn't answer with JSON. Check the My Domain URL."); sys.exit(1)
if "access_token" not in r:
    print("NO TOKEN: %s" % r.get("error", "no error code"))
    print("  invalid_client_id: the consumer key is wrong, or the app is new; wait 10 minutes and run this again.")
    print("  invalid_client: the consumer secret is wrong; copy it again from Consumer Key and Secret.")
    print("  Any other code: check that Enable Client Credentials Flow is selected and that Run As (Username) is the integration user.")
    sys.exit(1)
open(d + "/auth", "w").write("Authorization: Bearer " + r["access_token"] + "\n")
open(d + "/where", "w").write("%s\n%s\n" % (r["instance_url"], r["id"].rstrip("/").split("/")[-1]))
PY
  { read -r SF_INSTANCE; read -r SF_USER_ID; } < "$D/where"
  curl -sS -o "$D/user.json" -H @"$D/auth" -G "$SF_INSTANCE/services/data/v60.0/query" \
    --data-urlencode "q=SELECT Username FROM User WHERE Id = '$SF_USER_ID'" 2> "$D/curl.err"
  python3 -I - "$D" "$SF_USER_ID" <<'PY'
import json, sys
try:
    print("OK: the app issues tokens and runs as " + json.load(open(sys.argv[1] + "/user.json"))["records"][0]["Username"])
except Exception:
    print("OK: the app issues tokens and runs as the user with ID %s, but its username couldn't be read." % sys.argv[2])
PY
)
```

Don't deploy until it prints `OK: the app issues tokens and runs as` and the integration user's username. For any other output, see [External Client App and tokens](real-time-data-integration-troubleshoot.md#real-time-data-integration-troubleshoot-app).

You paste the consumer secret again in the first step of [Step 3: Deploy the CloudFormation stack](real-time-data-integration-resources.md), which stores it in AWS Secrets Manager. If you didn't keep it, copy it again from the External Client App's **Consumer Key and Secret**.