JWT (JSON Web Token) Bearer Token Flow is an OAuth 2.0 authentication mechanism in Salesforce, often used for server-to-server integrations without requiring interactive user authentication. It enables secure API access by exchanging a signed JWT for an access token.
This flow is particularly useful in scenarios where a client application needs to authenticate as a user without their direct involvement.
By the end of this tutorial, you will:
JWT Token Flow is an OAuth 2.0 authentication method in which a client application presents a signed JWT to obtain an access token. This allows secure, non-interactive authentication, making it ideal for backend integrations.
The process involves the following steps:
Use OpenSSL to generate a private key and certificate:
openssl genrsa -out private.key 2048
openssl req -new -x509 -key private.key -out public.crt -days 365
Upload public.crt
to the Salesforce Connected App.
The JWT structure consists of:
iss
, sub
, aud
, and exp
)Example JWT header:
{
"alg": "RS256",
"typ": "JWT"
}
Example JWT payload:
{
"iss": "Your_Consumer_Key",
"sub": "Salesforce_User_Username",
"aud": "https://login.salesforce.com",
"exp": 1712345678
}
Use a JWT library to sign the token with the private key:
openssl dgst -sha256 -sign private.key jwt_header_payload.json | base64
Alternatively, in Node.js:
const jwt = require('jsonwebtoken');
const fs = require('fs');
const privateKey = fs.readFileSync('private.key');
const token = jwt.sign(
{
iss: "Your_Consumer_Key",
sub: "salesforce_user@example.com",
aud: "https://login.salesforce.com",
exp: Math.floor(Date.now() / 1000) + 300
},
privateKey,
{ algorithm: 'RS256' }
);
console.log(token);
Make an HTTP POST request to Salesforce’s token endpoint:
curl -X POST https://login.salesforce.com/services/oauth2/token \
-d "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" \
-d "assertion=YOUR_SIGNED_JWT"
Upon successful authentication, Salesforce returns an access token:
{
"access_token": "00Dxx0000000000AAA",
"instance_url": "https://your-instance.salesforce.com",
"token_type": "Bearer"
}
Use this token to make API requests:
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
https://your-instance.salesforce.com/services/data/v59.0/sobjects/Account/
advantages
disadvantages
exp
claim should be within 5 minutes of the request.sub
(Subject Claim)
sub
should be an existing Salesforce username with the right permissions.aud
(Audience Claim)
"https://login.salesforce.com"
for production."https://test.salesforce.com"
for sandbox.JWT Token Flow in Salesforce is a powerful authentication mechanism for server-to-server communication. By correctly setting up a Connected App, JWT signing process, and token exchange, you can ensure a secure and seamless integration.
Additional Resources
https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_web_server_flow.htm&type=5