Skip to content

Instantly share code, notes, and snippets.

@jamesnicholls
Last active February 6, 2020 17:09
Show Gist options
  • Save jamesnicholls/aeba84e79a21d8a219955ab07e5305e0 to your computer and use it in GitHub Desktop.
Save jamesnicholls/aeba84e79a21d8a219955ab07e5305e0 to your computer and use it in GitHub Desktop.
Example of getting Salesforce access token using JWT bearer flow
const jwt = require('jsonwebtoken');
const {
SALESFORCE_CLIENT_ID,
SALESFORCE_AUTH_KEY,
SALESFORCE_USERNAME,
SALESFORCE_AUTH_HOST,
} = process.env;
function async getSalesforceAuthData() {
const payload = {
iss: SALESFORCE_CLIENT_ID,
aud: SALESFORCE_AUTH_HOST,
sub: SALESFORCE_USERNAME,
exp: Date.now() + (3 * 60 * 1000), // +3 minutes
};
const token = jwt.sign(payload, SALESFORCE_AUTH_KEY, { algorithm: 'RS256' });
const url = `${SALESFORCE_AUTH_HOST}/services/oauth2/token?grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=${token}`;
const response = await fetch(url, {
method: 'POST',
headers: {
accept: 'application/json',
},
});
return response.json();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment