SaasGuru Logo

Kickstart your career with the World's First Salesforce & AI Programs by an IIT - Explore Courses 🎉

Kickstart your career with the World's First Salesforce & AI Programs by an IIT - Explore Courses 🎉
Salesforce OAuth 2.0 JWT Bearer Flow: Secure Server-to-Server Integration

Salesforce OAuth 2.0 JWT Bearer Flow: Secure Server-to-Server Integration

The Salesforce platform offers a robust set of APIs for integrating external applications and extending functionalities. When it comes to server-to-server communication, the OAuth 2.0 JWT Bearer Flow emerges as a secure and efficient option. 

Understanding OAuth 2.0 JWT Bearer Flow

Traditional OAuth flows often involve user interaction, prompting users to log in and grant access. However, in server-to-server communication scenarios, such interaction is unnecessary. JWT Bearer Flow facilitates secure access token exchange without user intervention, streamlining automated processes between servers.

Core Components of the JWT Bearer Flow

    • JSON Web Token (JWT): A compact, self-contained unit of information containing claims (data) encoded in JSON format. It’s digitally signed using a cryptographic key, ensuring authenticity and integrity.
    • Connected App: A configuration within Salesforce representing the external application seeking access. It defines the level of access granted (scopes) and the signing certificate used for JWT verification.
    • Salesforce OAuth Token Endpoint: A specific URL within Salesforce responsible for issuing access tokens upon successful JWT validation.

saasguru salesforce labs

Prerequisites

  • Salesforce Developer Account: If you don’t have one, sign up at the Salesforce Developers site.
  • Connected App: Create a connected app in Salesforce with OAuth enabled.
  • Certificate: You’ll need a digital certificate to sign the JWT. You can use a  self-signed or CA signed or one generated by the 3rd party system which will call Salesforce using JWT token. .

Step-by-Step Implementation

Step 1: Create a Connected App in Salesforce

  1. Log into Salesforce and navigate to Setup.
  2. In the Quick Find box type “App Manager” and click on the option that appears.
  3. Click on “New Connected App” and enter the necessary details on the following screen
  4. Enable OAuth Settings and provide the callback URL (for JWT flow, this URL won’t be used but is required to enable OAuth).
  5. Under Selected OAuth Scopes, add the relevant scopes (e.g., Full access (full)).
  6. Be sure to copy and keep the Consumer Key and Consumer Secret for later use

Step 2: Generate a Digital Certificate

Generate a self-signed SSL certificate:

openssl req -newkey rsa:2048 -nodes -keyout server.key -x509 -days 365 -out server.crt

Upload this certificate to the connected app you created in Salesforce.

Step 3: Prepare the JWT

A JWT consists of three parts: Header, Payload, and Signature. Here’s how to construct it:

  • Header: Specify the algorithm and the token type.
  • Payload: Includes the issuer (Consumer Key from the connected app), audience (Salesforce OAuth endpoint), subject (username of the Salesforce user), and validity period.
  • Signature: Sign the JWT with the private key.

Example JWT Header (json):

{

  “alg”: “RS256”,

  “typ”: “JWT”

}

Example JWT Payload (json):

{

  “iss”: “YOUR_CONSUMER_KEY”,

  “sub”: “USER_EMAIL”,

  “aud”: “https://login.salesforce.com”,

  “exp”: “EXPIRATION_TIME”

}

Step 4: Sign and Encode the JWT

Use a library like jwt in Node.js to sign and encode your JWT (javascript):

const jwt = require(‘jsonwebtoken’);

const privateKey = fs.readFileSync(‘server.key’);

let token = jwt.sign(payload, privateKey, { algorithm: ‘RS256’});

Step 5: Obtain the Access Token

Make an HTTP POST request to the Salesforce OAuth endpoint with the JWT to receive the access token (javascript):

const request = require(‘request’);

let tokenEndpoint = ‘https://login.salesforce.com/services/oauth2/token’;

let sfdcClientId = ‘YOUR_CONSUMER_KEY’;

let jwtToken = ‘YOUR_JWT_TOKEN’;

let options = {

  method: ‘POST’,

  url: tokenEndpoint,

  headers: {

    ‘Content-Type’: ‘application/x-www-form-urlencoded’

  },

  form: {

    grant_type: ‘urn:ietf:params:oauth:grant-type:jwt-bearer’,

    assertion: jwtToken

  }

};

request(options, function (error, response, body) {

  if (error) throw new Error(error);

  console.log(body);

});

Upon successful authentication, Salesforce will return an access token which your application can use to make authenticated requests to Salesforce.

Advantages of Using JWT Bearer Flow

  • Enhanced Security: The JWT’s digital signature ensures data integrity and prevents unauthorized modification. Additionally, the flow eliminates the need to store client secrets on the server, further bolstering security.
  • Improved Efficiency: By removing user interaction, the JWT Bearer Flow streamlines server-to-server communication, making automated processes faster and more reliable.
  • Scalability: This flow is well-suited for high-volume server interactions, as it efficiently manages access token requests without user intervention.

Security Considerations for JWT Bearer Flow

  • Certificate Management: The private key used for signing JWTs must be meticulously guarded. Consider robust key management practices to prevent unauthorized access.
  • JWT Expiration: Ensure timely refresh of access tokens before they expire to avoid disruptions in server communication.
  • Claim Validation: Salesforce validates certain claims within the JWT. Double-check that your JWT construction includes the necessary and accurate claims.

Conclusion

Implementing the Salesforce OAuth 2.0 JWT Bearer Flow is a strategic step towards automating and securing your server-to-server interactions with Salesforce. This authentication method streamlines processes by removing the need for manual logins, thereby enabling seamless access to Salesforce’s vast resources. The steps and code examples provided in this guide aim to equip you with the knowledge to integrate this flow into your applications efficiently.  

To further your expertise and confidence in Salesforce, consider signing up with saasguru. Gain access to over 18 Salesforce Certification Courses, 50+ Mock Exams, and 50+ Salesforce Labs designed for hands-on learning. Whether you’re aiming to ace your next certification or seeking to deepen your understanding of Salesforce’s vast ecosystem, saasguru offers the resources and support to help you achieve your goals. 

Start your Salesforce journey with saasguru today!

Frequently Asked Questions (FAQs)

1. What is the OAuth 2.0 bearer token flow?

The OAuth 2.0 bearer token flow is a method for applications to obtain access tokens without user interaction. Clients simply present a bearer token (usually a JWT) to the authorization server, which validates it and grants access if valid. This flow is ideal for server-to-server communication.

2. How do I use JWT token for authentication in Salesforce?

Salesforce leverages the JWT Bearer Flow for server-to-server authentication. You construct a JWT containing claims about your server and desired access, sign it with a private key, and send it to the Salesforce OAuth token endpoint. Upon validation, Salesforce grants an access token for authorized API interactions.

3. Can I use JWT as a bearer token?

Absolutely! JWTs are a popular choice for bearer tokens due to their compact size, self-contained nature, and digital signature capabilities. This signature ensures the token’s integrity and prevents unauthorized modification.

4. What is the JWT bearer grant type flow?

The JWT bearer grant type flow is a specific terminology not officially defined in the OAuth 2.0 specification. However, it commonly refers to the use of JWTs within the OAuth 2.0 Bearer Token Flow, as described earlier.

5. What is the difference between JWT and OAuth 2.0?

JWT (JSON Web Token) is a data format for securely transmitting information between parties. It can be used within various authentication flows, including OAuth 2.0. OAuth2, on the other hand, is a framework defining authorization protocols for applications to access user accounts on other services. The JWT Bearer Flow combines these concepts, using JWTs for secure token exchange within the OAuth 2.0 framework.

6. What is the difference between JWT and authorization header bearer?

A JWT is the actual token containing claims and a signature. The “Authorization Header Bearer” refers to the HTTP header used to transmit the JWT during communication. It specifies the type of token being sent (bearer) and includes the actual JWT itself.

7. What are the three types of JWT?

There are not strictly three defined “types” of JWTs. However, JWTs can be categorized based on their usage:

  • JWT for Signing: Used to transmit information with a verifiable signature, ensuring data integrity.
  • JWT for Encryption: Encrypted JWTs require a shared secret key for decryption, offering an additional layer of confidentiality.
  • JWT for Both: JWTs can be both signed and encrypted for maximum security, combining data integrity verification with confidentiality.

8. How does the JWT bearer token work?

The JWT Bearer Flow involves these steps:

  • You generate a JWT containing claims about your server and desired access.
  • You sign the JWT with your private key.
  • Your server transmits the signed JWT to the Salesforce OAuth token endpoint.
  • Salesforce validates the JWT against the public key associated with your connected app.
  • If valid, Salesforce issues an access token for authorized API interactions.

9. What is the difference between OAuth 2.0 and bearer token authentication?

OAuth2 is a broader framework defining various authorization flows, including the Bearer Token Flow. Bearer token authentication, on the other hand, refers to the specific method of using bearer tokens (often JWTs) to access resources without requiring separate user credentials each time. The JWT Bearer Flow leverages both OAuth2 and bearer token authentication for secure server-to-server communication.

Table of Contents

Subscribe & Get Closer to Your Salesforce Dream Career!

Get tips from accomplished Salesforce professionals delivered directly to your inbox.

Looking for Career Upgrade?

Book a free counselling session with our Course Advisor.

By providing your contact details, you agree to our Terms of use & Privacy Policy

Unlock Your AI -Powered Assistant

Gain Exclusive Access to Your Salesforce Copilot

Related Articles

Salesforce Job Market in 2025: Key Trends and Factors You Should Know

Explore the 2025 Salesforce job market trends, key factors, and strategies to thrive in an evolving digital landscape. Read now!

Humans of Salesforce – Sara Hernandez

Discover how Sara Hernandez transformed from an ‘Accidental Admin’ into a passionate Salesforce trailblazer. Read now!

New courses launched by IITs in 2024

Explore IITs’ new 2024 courses in Salesforce, AI, Data Science, Robotics & more. Advance your career with industry-aligned programs!