Skip to content

Instantly share code, notes, and snippets.

@davidmreed
Created January 15, 2019 01:32
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save davidmreed/5f4b7b8436487f9da9f682ca97f12cd9 to your computer and use it in GitHub Desktop.
Save davidmreed/5f4b7b8436487f9da9f682ca97f12cd9 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'])
@alex-todorov
Copy link

what type of key should be the private_key pem?

@davidmreed
Copy link
Author

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.

@KandarpPatel07
Copy link

KandarpPatel07 commented May 31, 2022

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