Skip to content

Add support for JWT Bearer Flow #97

@AndrewRayCode

Description

@AndrewRayCode

This library does not support the required and best practice authentication mechanism of the "JWT Bearer Flow" https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_jwt_flow.htm&language=en_US&type=5 .

This is the standard way of doing machine to machine OAuth. You have support for setRefreshToken() but this isn't helpful as the standard JWT bearer flow Oauth is what you need to to in order to get a token in the first place. Semi-related, the Ruby restforce gem has similar confusion and missing features around JWT bearer flow.

FWIW here's what it looks like in a Postman pre-request script to get a proper access token with Salesorce, where you build a JWT with claims, sign it with the private key (part of the JWT bearer flow), and gets back an access token that's valid for a few hours:

var navigator = {};
var window = {};

const jwt_header = {
  "alg": "RS256",
  "typ": "JWT"
};
const jwt_claims = {
  "iss": pm.collectionVariables.get("SALESFORCE_CONSUMER_KEY"),
  "sub": pm.collectionVariables.get("SALESFORCE_USERNAME"),
  "aud": "https://test.salesforce.com",
  "exp": Date.now() + 10000
};
const private_key = atob(pm.collectionVariables.get("SALESFORCE_PRIVATE_KEY"));

pm.sendRequest({
  url: 'http://kjur.github.io/jsrsasign/jsrsasign-latest-all-min.js',
  method: 'GET'
}, function (err, res) {
    eval(res.text());

    const signedJwt = KJUR.jws.JWS.sign('RS256', JSON.stringify(jwt_header), JSON.stringify(jwt_claims), private_key);
    // console.log('Assertion to send to Salesforce:', signedJwt);

    pm.sendRequest({
    url: pm.collectionVariables.get("SALESFORCE_TOKEN_URL"),
    method: 'POST',
    header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: {
        mode: 'urlencoded',
            urlencoded: [
            { key: "grant_type", value: "urn:ietf:params:oauth:grant-type:jwt-bearer", disabled: false },
            { key: "assertion", value: signedJwt, disabled: false}
        ]
    }
    }, function (err, res) {
        console.log('Auth err:', err, ' Auth res', res.json());
        pm.environment.set("instance_url", res.json().instance_url);
        pm.environment.set("authorization", res.json().access_token);
    });

});

It looks like this library may be abandonware, are there any forks which add this required auth mechanism?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions