Skip to content

Instantly share code, notes, and snippets.

@kheast
Forked from davidmreed/simple-salesforce-jwt.py
Created January 30, 2022 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kheast/041a79cf89cd36d2eab27e53f8598593 to your computer and use it in GitHub Desktop.
Save kheast/041a79cf89cd36d2eab27e53f8598593 to your computer and use it in GitHub Desktop.
Using simple_salesforce with JWT authentication
import jwt
import requests
import datetime
from simple_salesforce import Salesforce
from simple_salesforce.exceptions import SalesforceAuthenticationFailed
def jwt_login(consumer_id, username, private_key, sandbox=False):
endpoint = 'https://test.salesforce.com' if sandbox is True else 'https://login.salesforce.com'
jwt_payload = jwt.encode(
{
'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=30),
'iss': consumer_id,
'aud': endpoint,
'sub': username
},
private_key,
algorithm='RS256'
)
result = requests.post(
endpoint + '/services/oauth2/token',
data={
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': jwt_payload
}
)
body = result.json()
if result.status_code != 200:
raise SalesforceAuthenticationFailed(body['error'], body['error_description'])
return Salesforce(instance_url=body['instance_url'], session_id=body['access_token'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment