/
jwtflow.js
53 lines (43 loc) · 1.13 KB
/
jwtflow.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
var request = require('request');
var jwt = require('jsonwebtoken');
module.exports = function (clientId, privateKey, userName, sandbox, cb) {
var options = {
issuer: clientId,
expiresInMinutes: 3,
algorithm:'RS256',
audience: sandbox ? 'https://test.salesforce.com' : 'https://login.salesforce.com'
}
var token = jwt.sign({ prn: userName }, privateKey, options);
var post = {
form: {
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': token
},
method: 'post',
uri: sandbox ? 'https://test.salesforce.com/services/oauth2/token' : 'https://login.salesforce.com/services/oauth2/token'
}
request(post, function(err, res, body) {
if (err) {
cb(err);
return;
};
var reply = JsonTryParse(body);
if (!reply) {
cb(new Error('No response from oauth endpoint.'));
return;
};
if (res.statusCode != 200) {
var message = 'Unable to authenticate: ' + reply.error + ' (' + reply.error_description + ')';
cb(new Error(message))
return;
};
cb(null, reply.access_token);
});
}
function JsonTryParse(string) {
try {
return JSON.parse(string);
} catch (e) {
return null;
}
}