Salesforce Auth - JWT Bearer Flow

Notes and steps on implementing the JWT Bearer Flow method for authenticating between Salesforce and other Server-based applications (like CLIs or web servers). Largely based on OAuth standards

Use Cases

Steps for JWT Setup

  1. Validate that you have openssl installed. Note: it’s not needed on the machine running the CI all the time, just for generating the certificate once
    1. If you don’t, install it -> This will be used for generating the X.509 Certificate
  2. Create a Self-Signed SSL Certificate and Private Key (see commands below in Commands for Generating the Certificate)
  3. Create Connected App in Salesforce Org. Include the following settings:
    1. Enable OAuth Settings
    2. Callback URL
    3. Use Digital Signatures
      1. Upload the .crt file that was generated above here
    4. Correct OAuth scopes
  4. Copy the consumer key for later use
  5. Save Connected App and Edit policies: Select Admin approved users are pre-authorized
  6. Create a Permission Set to assign pre-authorized users for the connected App
  7. Navigate back to Connected App > Manage Permission Sets
    1. Add the newly-created Permission Set to show this is the one that pre-authorizes the users
  8. Test the JWT Auth Flow (see Commands for Testing the JWT Auth Flow)

Commands for Generating the Certificate

# Generate RSA Private Key
openssl genrsa -des3 -passout pass:SomePassword -out server.pass.key 2048

# Create key file from Key
openssl rsa -passin pass:SomePassword -in server.pass.key -out server.key

# Delete Key
rm server.pass.key

# Generate Certificate
openssl req -new -key server.key -out server.csr

# Fill in all info
# NOTE: Don't worry about the challenge password since it's self signed

# Generate SSL Cert
openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt

# Validate that you have the following 3 files:
# server.crt -> Site certificate
# server.csr
# server.key -> Private key, used to generate the JWT (so it'll be needed on the server making calls)

Commands for Testing the JWT Auth Flow - Bash

export CONSUMER_KEY=<connected app consumer key>
export JWT_KEY_FILE=<example: /users/yourname/certificates/server.key>
export HUB_USERNAME=<your Dev Hub username>

sfdx auth:jwt:grant --clientid ${CONSUMER_KEY} \
                    --username ${HUB_USERNAME} \
                    --jwtkeyfile ${JWT_KEY_FILE} \
                    --setdefaultdevhubusername

Notes

Further Reading / Research

Tags

References