Salesforce is a powerful CRM platform, and connecting to it securely is crucial for accessing and managing data. One of the secure methods to connect with Salesforce is using JSON Web Tokens (JWT). JWT authentication is especially useful for server-to-server integrations where user interaction is not required. This blog post will guide you through the process of setting up JWT authentication with Salesforce.
Steps to Implement JWT Authentication with Salesforce
1. Create a Connected App in Salesforce
- Navigate to Setup: Log in to your Salesforce org and go to the Setup area.
- App Manager: In the Quick Find box, type “App Manager” and select it.
- New Connected App: Click on “New Connected App”.
- Basic Information: Fill in the required fields like Connected App Name, API Name, and Contact Email.
- Enable OAuth Settings:
- Check the “Enable OAuth Settings” checkbox.
- In the “Callback URL” field, enter a placeholder URL (e.g.,
http://localhost:3000/callback). - Select the following OAuth Scopes:
Manage user data via APIs (api)Perform requests on your behalf at any time (refresh_token, offline_access)
- Check the “Use Digital Signatures” checkbox and upload your certificate (public key).
- Save: Click “Save” and note down the Consumer Key (Client ID).
2. Generate a Private Key and Certificate
If you don’t have a private key and certificate, you can generate them using OpenSSL. Check this article to download OpenSSL.
Here’s how you can create a private key and a self-signed certificate:
- Generate the Private Key:
openssl genrsa -out server.key 2048 - Create a Certificate Signing Request (CSR):
openssl req -new -key server.key -out server.csr
During this step, you’ll be prompted to enter some information about your organization and domain. - Generate the Self-Signed Certificate:
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
3. Run the org login jwt CLI command
sf org login jwt --client-id 3MVG9pRxf --jwt-key-file server.key --username stockmaster@wiseinvesting.com --alias my-hub-org --instance-url https://login.salesforce.com
If encounter below error, it means you need to approve this user first time.
Errors encountered:
user hasn’t approved this consumer
Use below command to approve the user first time-