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.
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.
- Login to salesforce.
- Go to setup area (gear in the nav in the top right)
- In the side nav, go to Apps > App Manager
- Click New Connect App
- In the Basic Information section, populate the required fields. The values are for book keeping only and are not part of using the API.
- In the API (Enable OAuth Settings) section:
- Check Enable OAuth Settings
- Callback URL is unused in the JWT flow but a value is required nonetheless. Use "http://localhost/" or some other dummy host.
- Check Use digital signatures. Upload the salesforce.crt that was generated earlier.
- For Selected OAuth Scopes, add Access and manage your data (api) and Perform requests on your behalf at any time (refresh_token, offline_access)
- Click Save. If there are any errors, you have to re-upload salesforce.crt.
- On the resulting app page, click Manage.
- Click Edit Policies.
- In the OAuth policies section, change Permitted Users to Admin approved users are pre-authorized.
- Click Save.
- Back on the app page again, in the Profiles section, click Manage Profiles.
- On the Application Profile Assignment page, assign the user profiles that will have access to this app.
To use the API, the RSA private key and the Consumer Key (aka client ID) from the Salesforce application are needed.
- The private key is the key that was generated in the Prequisite section above.
- To get the Salesforce application Consumer Key, do the following
- Login to salesforce.
- Go to setup area (gear in the nav in the top right)
- In the side nav, go to Apps > App Manager
- In the list, find the application that you created in the App Creation section above
- From the drop down in the application's row, click View
- The Consumer Key is in the API (Enable OAuth Settings) section.
- To see successful OAuth logins, see the Session Management page.
- Help: https://salesforce.stackexchange.com/questions/207685
- For more info including a poorly done Java example, see https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm&type=5
On top of changing
jwt
topyjwt
onpip install
, I encountered an error:This can be fixed by removing
.decode('utf8')
on the assertion, from:to:
Once this is removed, this code runs successfully 🎉