Last active
November 25, 2018 10:24
-
-
Save hyrsky/b11ad97c6ce5161ee4abf818301de2f7 to your computer and use it in GitHub Desktop.
Salesforce oauth example
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
#!/usr/bin/env python | |
import os | |
import pprint | |
import json | |
from requests_oauthlib import OAuth2Session, TokenUpdated | |
TOKEN_FILE = os.environ.get('TOKEN_FILE', 'token.json') | |
SALESFORCE_URI = os.environ.get('SALESFORCE_URI', 'https://login.salesforce.com') | |
CONSUMER_KEY = os.environ.get('CONSUMER_KEY') | |
CONSUMER_SECRET = os.environ.get('CONSUMER_SECRET') | |
REDIRECT_URI = os.environ.get('REDIRECT_URI') | |
pp = pprint.PrettyPrinter(indent=2) | |
if not os.path.isfile(TOKEN_FILE): | |
# OAuthLib forbids insecure urls by default | |
if REDIRECT_URI.startswith('http://'): | |
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' | |
oauth = OAuth2Session(CONSUMER_KEY, redirect_uri=REDIRECT_URI) | |
authorization_url, state = oauth.authorization_url( | |
SALESFORCE_URI + '/services/oauth2/authorize', access_type="offline") | |
print ('Please go to:\n%s' % authorization_url) | |
authorization_response = input('Enter the full callback URL:\n') | |
token = oauth.fetch_token( | |
SALESFORCE_URI + '/services/oauth2/token', | |
authorization_response=authorization_response, | |
client_secret=CONSUMER_SECRET | |
) | |
with open(TOKEN_FILE, 'w') as f: | |
json.dump(token, f) | |
else: | |
print ('Using token from %s' % TOKEN_FILE) | |
with open(TOKEN_FILE, 'r') as f: | |
token = json.load(f) | |
pp.pprint(token) | |
extra = { | |
'client_id': CONSUMER_KEY, | |
'client_secret': CONSUMER_SECRET, | |
} | |
try: | |
# Create autorefreshing session | |
client = OAuth2Session(CONSUMER_KEY, token=token, | |
auto_refresh_kwargs=extra, | |
auto_refresh_url=SALESFORCE_URI + '/services/oauth2/token') | |
# Get protected url using oauth token | |
r = client.get(SALESFORCE_URI + '/services/apexrest/myrest') | |
pp.pprint(r.content) | |
except TokenUpdated as e: | |
pp.pprint('Refreshed token:', e.token) | |
with open(TOKEN_FILE, 'w') as f: | |
json.dump(token, f) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment