Created
January 15, 2019 01:32
-
-
Save davidmreed/5f4b7b8436487f9da9f682ca97f12cd9 to your computer and use it in GitHub Desktop.
Using simple_salesforce with JWT authentication
This file contains hidden or 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']) |
There's an example in the PyJWT docs (https://pyjwt.readthedocs.io/en/stable/usage.html). It's the textual format in a keyfile as generated by OpenSSL.
How to generate X509 certificate and use that to generate to get JWT token I am having certificate and private key
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what type of key should be the private_key pem?