Sub topic 15
Authorizing a Dev Hub in automation
This chapter assumes you have already enabled Dev Hub and run sf org login web --set-default-dev-hub by hand. It also assumes you can read a short YAML pipeline. The browser login is a good fit for your laptop. A CI job has no browser and no person to type a password, so it needs a non-interactive way to authorize the Dev Hub.
Why the browser login does not work in CI
sf org login web opens a browser, waits for you to log in, and stores a refresh token on your machine. A build agent is usually a fresh, disposable machine with no display. Two non-interactive options cover most cases:
| Method | Command | What the pipeline stores | Best for |
|---|---|---|---|
| JWT bearer flow | `sf org login jwt` | A private key and a connected app consumer key | Production pipelines, shared teams |
| SFDX auth URL | `sf org login sfdx-url` | One secret string that contains a refresh token | Quick setups, small projects |
Both methods end with the same result. The CLI has an authorized Dev Hub that you can use to create scratch orgs.
JWT bearer flow
In the JWT flow, the pipeline proves its identity by signing a short token with a private key. Salesforce checks the signature against a certificate you uploaded to a connected app. No password and no interactive consent are involved.
Step 1: Create a key pair
Create a private key and a self-signed certificate. You run this once, on a trusted machine.
openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 \
-keyout server.key -out server.crt \
-subj "/CN=ci-devhub"server.key is the secret. Never commit it. server.crt is the public half and is safe to upload. Because the certificate expires in 365 days, put a renewal reminder in your calendar.
Step 2: Create a connected app in the Dev Hub org
In Setup, open App Manager and create a new connected app. Use these settings:
- Turn on Enable OAuth Settings.
- Set the callback URL to
http://localhost:1717/OauthRedirect. The field is required even though the JWT flow never uses it. - Turn on Use digital signatures and upload
server.crt. - Add the OAuth scopes Manage user data via APIs (api) and Perform requests at any time (refreshtoken, offlineaccess).
- Save, then copy the Consumer Key. The CLI calls this the client ID.
Step 3: Pre-authorize the user
The JWT flow never shows a consent screen, so the connected app must already trust the user. Open Manage for the connected app, then Edit Policies. Set Permitted Users to Admin approved users are pre-authorized. Then assign a profile or permission set that includes the user who will log in. If you skip this step, login fails with a "user hasn't approved this consumer" error.
Use a dedicated integration user instead of a person's account. That user needs permission to use the Dev Hub and to create scratch orgs. A password change or a departure then cannot break your pipeline.
Step 4: Log in with the key
sf org login jwt \
--client-id 3MVG9ExampleConsumerKey \
--jwt-key-file server.key \
--username [email protected] \
--instance-url https://login.salesforce.com \
--set-default-dev-hub \
--alias ci-hubEach flag has a specific job:
--client-idis the connected app's consumer key.--jwt-key-filepoints to the private key.--usernameis the user who will act in the org.--instance-urlis the login endpoint. For a Dev Hub in production or Developer Edition, usehttps://login.salesforce.com. For a sandbox or a My Domain with a custom URL, use that URL instead.--set-default-dev-huband--aliaswork the same as in the interactive login.
Confirm the result with sf org list. The Dev Hub should appear with the alias ci-hub.
SFDX auth URL
The auth URL method wraps a refresh token in a single string. You authorize once in a browser, export the string, and store it as a CI secret.
sf org login web --set-default-dev-hub --alias my-hub
sf org display --target-org my-hub --verbose --jsonIn the JSON output, find result.sfdxAuthUrl. Save that value into a file named authurl.txt, then load it in the pipeline:
sf org login sfdx-url --sfdx-url-file authurl.txt --set-default-dev-hub --alias ci-hubThis is faster to set up because it needs no connected app work. It has trade-offs:
- The string is a long-lived credential tied to a real user. Anyone who reads it can act as that user.
- If the user's session is revoked or the user is deactivated, the refresh token stops working.
- A Dev Hub authorized through JWT has no refresh token, so
sfdxAuthUrlis empty for it. Only web-login orgs produce the string.
A complete pipeline
This GitHub Actions job authorizes the Dev Hub, creates a one-day scratch org, deploys, and always cleans up. The three secrets are SF_JWT_KEY (the full contents of server.key), SF_CLIENT_ID, and SF_DEVHUB_USER.
name: scratch-org-ci
on: pull_request
jobs:
test:
runs-on: ubuntu-latest
env:
SF_CLIENT_ID: ${{ secrets.SF_CLIENT_ID }}
SF_DEVHUB_USER: ${{ secrets.SF_DEVHUB_USER }}
SF_JWT_KEY: ${{ secrets.SF_JWT_KEY }}
steps:
- uses: actions/checkout@v4
- name: Install Salesforce CLI
run: npm install --global @salesforce/cli
- name: Authorize Dev Hub
run: |
printf '%s\n' "$SF_JWT_KEY" > "$RUNNER_TEMP/server.key"
sf org login jwt \
--client-id "$SF_CLIENT_ID" \
--jwt-key-file "$RUNNER_TEMP/server.key" \
--username "$SF_DEVHUB_USER" \
--instance-url https://login.salesforce.com \
--set-default-dev-hub \
--alias ci-hub
- name: Create scratch org
run: |
sf org create scratch \
--definition-file config/project-scratch-def.json \
--alias ci-scratch \
--duration-days 1 \
--set-default \
--wait 10
- name: Deploy source
run: sf project deploy start --target-org ci-scratch
- name: Clean up
if: always()
run: |
sf org delete scratch --target-org ci-scratch --no-prompt || true
rm -f "$RUNNER_TEMP/server.key"Several choices in this file matter:
--duration-days 1keeps the scratch org short-lived, so a failed cleanup does not hold a slot for a week.--wait 10makes the command block for up to 10 minutes, so the next step does not start before the org exists.if: always()runs the cleanup step even when an earlier step fails.|| truestops a failed delete from hiding the real error from an earlier step.
Operating it safely
Concurrent pipelines share one Dev Hub, so they share its active and daily scratch org limits. Before you run many parallel jobs, check the numbers with sf limits api display --target-org ci-hub. Look at the ActiveScratchOrgs and DailyScratchOrgs rows. When a job fails with a limit error, the cause is often leaked orgs from earlier runs that never reached the cleanup step.
Add --json to any CLI command when a script needs to read the result. Check the process exit code, because the CLI returns a non-zero code when a command fails.
Common login failures in automation:
| Symptom | Likely cause |
|---|---|
| `invalid_grant: user hasn't approved this consumer` | The connected app does not pre-authorize the user. Fix the policy and the profile or permission set. |
| `invalid_client_id` | Wrong consumer key, or the connected app is not yet active. Newly created apps can take a few minutes. |
| `invalid_grant: audience is invalid` | Wrong `--instance-url`. Use the URL that matches the org type. |
| Signature or key errors | The private key does not match the uploaded certificate, or the secret lost its line breaks. |
Exercise
Your pipeline uses sf org login jwt to authorize the Dev Hub. You run sf org display --target-org ci-hub --verbose --json and find that sfdxAuthUrl is empty. Is something broken, and how would you get an auth URL if you wanted one?
Show answer
Nothing is broken. A JWT login does not receive a refresh token, so no auth URL exists for that org. To get one, authorize the Dev Hub with sf org login web, then run sf org display --verbose --json on that org and read result.sfdxAuthUrl.
Exercise
A CI job fails during sf org login jwt with "user hasn't approved this consumer", even though the consumer key and key file are correct. Name the two settings you check in Setup.
Show answer
Check that the connected app's Permitted Users policy is set to "Admin approved users are pre-authorized", and that the login user has a profile or permission set assigned to that connected app.