Skip to content

Instantly share code, notes, and snippets.

@v-rudkov
Last active May 19, 2019 20:45
Show Gist options
  • Save v-rudkov/8497a2ce74cea0493fb13a326b93056d to your computer and use it in GitHub Desktop.
Save v-rudkov/8497a2ce74cea0493fb13a326b93056d to your computer and use it in GitHub Desktop.
SFDX CLI: Getting Access Tokens

SFDX CLI: Getting Access Tokens

Once we authorized an org we got an access token for that org and we can use it for our needs. To get the access token use force:org:display command:

$ sfdx force:org:display

=== Org Description
KEY              VALUE
───────────────  ────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Access Token     00D1x0000000TA9!AQ8AQBvjAlvfkyyvGHna2LYGuyTGgH_4nghoByc2iw0EQ_WOOL_ai8zUsqdbPBQXCEAoGbpJ3v3uPTz8FTszQ8RUTfCTTK1B
Alias            scratch1
Client Id        PlatformCLI
Created By       v.rudkov@resourceful-badger-118315.com
Created Date     2019-05-17T09:36:06.000+0000
Dev Hub Id       v.rudkov@resourceful-badger-118315.com
Edition          Developer
Expiration Date  2019-05-24
Id               00D1x0000000TA9EAM
Instance Url     https://computing-drive-2218-dev-ed.cs100.my.salesforce.com/
Org Name         vadim Company
Status           Active
Username         test-wfxgkj0ck8ou@example.com

This little bash script makes this process more handy:

#!/bin/bash

if [[ $# -gt 0 ]] ; then
    alias="-u $1"
fi

sfdx force:org:display $alias --json | jq -r '.result.accessToken'

The same approach can be used to retrieve the instance url.

Just copy these scripts to the location where executable files are stored:

$ sudo cp token /usr/local/bin
$ sudo cp instance_url /usr/local/bin

If it is run without argument the default org is used. It also accepts one parameter which can be alias or username:

$ token org_alias

Now we can use it for further requests:

curl "$(instance_url)/services/data/v45.0/query/?q=select+name+from+Lead+limit+1" \
-H "Authorization: Bearer $(token)" \
-H "X-PrettyPrint:1"

{
  "totalSize" : 1,
  "done" : true,
  "records" : [ {
    "attributes" : {
      "type" : "Lead",
      "url" : "/services/data/v45.0/sobjects/Lead/00Q1t000002JgI2EAK"
    },
    "Name" : "Bertha Boxer"
  } ]
}
#!/bin/bash
if [[ $# -gt 0 ]] ; then
alias_or_username="-u $1"
fi
sfdx force:org:display $alias_or_username --json | jq -r '.result.instanceUrl'
#!/bin/bash
if [[ $# -gt 0 ]] ; then
alias="-u $1"
fi
sfdx force:org:display $alias --json | jq -r '.result.accessToken'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment