Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SFoskitt/92b792b4e01ee56d6dea7d79717fb141 to your computer and use it in GitHub Desktop.
Save SFoskitt/92b792b4e01ee56d6dea7d79717fb141 to your computer and use it in GitHub Desktop.
Salesforce OAuth 2.0 JWT Bearer Token Flow walk-through

Salesforce OAuth 2.0 JWT Bearer Token Flow Walk-Through

This document will walk you through how to create or configure a Salesforce application for use with JWT authentication. These configuration steps and the example code works as of Salesforce API version 42.0.

Prerequisites

Create an RSA x509 private key/certification pair

openssl req -x509 -sha256 -nodes -days 36500 -newkey rsa:2048 -keyout salesforce.key -out salesforce.crt

The private key (.key) will be used to sign the JWT claim generated by your code. The certificate (.crt) will be uploaded to Salesforce to validate your signed JWT assertions.

Salesforce Application creation

  1. Login to salesforce.
  2. Go to setup area (gear in the nav in the top right)
  3. In the side nav, go to Apps > App Manager
    1. Click New Connect App
    2. In the Basic Information section, populate the required fields. The values are for book keeping only and are not part of using the API.
    3. In the API (Enable OAuth Settings) section:
      1. Check Enable OAuth Settings
      2. Callback URL is unused in the JWT flow but a value is required nonetheless. Use "http://localhost/" or some other dummy host.
      3. Check Use digital signatures. Upload the salesforce.crt that was generated earlier.
      4. For Selected OAuth Scopes, add Access and manage your data (api) and Perform requests on your behalf at any time (refresh_token, offline_access)
    4. Click Save. If there are any errors, you have to re-upload salesforce.crt.
  4. On the resulting app page, click Manage.
    1. Click Edit Policies.
    2. In the OAuth policies section, change Permitted Users to Admin approved users are pre-authorized.
    3. Click Save.
  5. Back on the app page again, in the Profiles section, click Manage Profiles.
    1. On the Application Profile Assignment page, assign the user profiles that will have access to this app.

OAuth Access Configuration

To use the API, the RSA private key and the Consumer Key (aka client ID) from the Salesforce application are needed.

  1. The private key is the key that was generated in the Prequisite section above.
  2. To get the Salesforce application Consumer Key, do the following
    1. Login to salesforce.
    2. Go to setup area (gear in the nav in the top right)
    3. In the side nav, go to Apps > App Manager
    4. In the list, find the application that you created in the App Creation section above
    5. From the drop down in the application's row, click View
    6. The Consumer Key is in the API (Enable OAuth Settings) section.

Parting Tips

# pip install jwt cryptography requests
from datetime import datetime
import jwt
import time
import requests
# *** Update these values to match your configuration ***
IS_SANDBOX = True
KEY_FILE = 'salesforce.key'
ISSUER = 'the consumer key from your application'
SUBJECT = 'your-sf-user@email.tld'
# *******************************************************
DOMAIN = 'test' if IS_SANDBOX else 'login'
print('Loading private key...')
with open(KEY_FILE) as fd:
private_key = fd.read()
print('Generating signed JWT assertion...')
claim = {
'iss': ISSUER,
'exp': int(time.time()) + 300,
'aud': 'https://{}.salesforce.com'.format(DOMAIN),
'sub': SUBJECT,
}
assertion = jwt.encode(claim, private_key, algorithm='RS256', headers={'alg':'RS256'}).decode('utf8')
print('Making OAuth request...')
r = requests.post('https://{}.salesforce.com/services/oauth2/token'.format(DOMAIN), data = {
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': assertion,
})
print('Status:', r.status_code)
print(r.json())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment