-
-
Save kheast/041a79cf89cd36d2eab27e53f8598593 to your computer and use it in GitHub Desktop.
Using simple_salesforce with JWT authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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