How to Authenticate with Salesforce Using JWT

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

  1. Navigate to Setup: Log in to your Salesforce org and go to the Setup area.
  2. App Manager: In the Quick Find box, type “App Manager” and select it.
  3. New Connected App: Click on “New Connected App”.
  4. Basic Information: Fill in the required fields like Connected App Name, API Name, and Contact Email.
  5. 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).
  6. 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:

  1. Generate the Private Key:
    openssl genrsa -out server.key 2048
  2. 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.
  3. 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-

https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=3MVG9pRxf&redirect_uri=https://wiseinvesting3-dev-ed.develop.lightning.force.com/

Published by Sandeep Kumar

He is a Salesforce Certified Application Architect having 11+ years of experience in Salesforce.

Leave a Reply