Skip to content

Instantly share code, notes, and snippets.

@jcdyer
Last active October 1, 2015 17:58
Show Gist options
  • Save jcdyer/d4401e941f12124ffed2 to your computer and use it in GitHub Desktop.
Save jcdyer/d4401e941f12124ffed2 to your computer and use it in GitHub Desktop.
This script will generate an OAuth bearer token for use in curl or python scripts that use requests.
#!/usr/bin/env python
"""
Get a bearer token for the requested user/pass.
Must have environment variable OAUTH_CLIENT_ID defined
"""
from __future__ import absolute_import, print_function, unicode_literals
import sys, os
import requests
HOST = os.environ.get('OAUTH_HOST', 'http://localhost:8000')
USAGE = '''
Usage: {} <username> <password>
Required environment variable:
OAUTH_CLIENT_ID: Set to OAuth 2 client id (see: /admin/oauth2/client/)
Optional environment variable:
OAUTH_HOST: Set to the host prefix of your edx app. Defaults to
http://localhost:8000
'''
def get_token(session, username, password):
"""
Attach a bearer token to the requests session, and return its value
"""
client_id = os.environ['OAUTH_CLIENT_ID']
url = '{}/oauth2/access_token/'.format(HOST)
params = {
'client_id': client_id,
'grant_type': 'password',
'username': username,
'password': password
}
response = session.post(url, data=params)
if not response.ok:
raise ValueError("An error occurred: {}".format(response.text))
token = response.json()['access_token']
token_type = response.json()['token_type']
session.headers['Authorization'] = ' '.join([token_type, token])
return token
def main():
"""Execute the script"""
session = requests.Session()
if len(sys.argv) != 3:
print(USAGE)
sys.exit(1)
print(get_token(session, sys.argv[1], sys.argv[2]))
if __name__ == '__main__':
main()
COMMAND LINE:
$ export OAUTH_CLIENT_ID=ffffbbbb777733330000
$ oauthtoken.py staff edx
3bae7d8cf43a69e34a35188636c3553e8b52a89c
$ token=`oauthtoken.py staff edx`
$ curl -H "Authorization: Bearer $token" http://localhost:8000/api/user/v1/accounts/staff
{"username":"staff",...}
PYTHON
>>> import requests
>>> import oauthtoken
>>> s = requests.Session()
>>> oauthtoken.get_token(s, 'staff', 'edx')
>>> response = s.get('http://localhost:8000/api/user/v1/accounts/staff')
>>> print response.json()
{'username': 'staff', ...}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment