Skip to content

Instantly share code, notes, and snippets.

@jhw
Last active November 26, 2022 21:33
Show Gist options
  • Save jhw/ca3cd3079e9b7bdce6d45fb693410288 to your computer and use it in GitHub Desktop.
Save jhw/ca3cd3079e9b7bdce6d45fb693410288 to your computer and use it in GitHub Desktop.
Quizlet OAuth example
export BROWSER=google-chrome

https://quizlet.com/api-dashboard

Need client_id and client_secret from API homepage, stored in tmp/config.yaml

client_id: "#{client_id}"
client_secret: "#{client_secret}"
redirect_uri: "https://www.mozilla.org/en-US/"
justin@justin-XPS-13-9360:~/work$ python3 authorize.py 
Open your browser and navigate to new tab
Paste the full redirect URL here - Opening in existing browser session.
https://www.mozilla.org/en-US/?code=XXXXXX&state=XXXXXX
{'access_token': 'XXXXXX', 'token_type': 'bearer', 'scope': ['XXXXXX']}

- script should fire up your webbrowser, open a new tab and navigate to the URL specified by `redirect_uri`
- note args appended to end of redirect URL

- *copy/paste that URL from the browser into the terminal to complete the flow and get the token*

"""
- https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/
- https://stackoverflow.com/questions/32397338/aws-codepipeline-not-able-to-access-organizations-repositories
"""
import json, re, requests, webbrowser, yaml
from requests_oauthlib import OAuth2Session
AuthURL="https://quizlet.com/authorize"
TokenURL="https://api.quizlet.com/oauth/token"
Scopes=yaml.load("""
- read
- write_set
""", Loader=yaml.FullLoader)
def authorize(config):
session=OAuth2Session(config["client_id"],
scope=Scopes, # NB not comma- joined string
redirect_uri=config["redirect_uri"])
auth, state = session.authorization_url(AuthURL,
access_type="offline",
approval_prompt="force")
print ("Open your browser and navigate to new tab")
webbrowser.open(auth)
response=input("Paste the full redirect URL here - ")
try:
code=re.search("(code=)(.+)", response).group(2)
except:
raise RuntimeError("Failed to filter code from pasted data")
return session.fetch_token(TokenURL,
client_secret=config["client_secret"],
authorization_response=response)
if __name__=="__main__":
try:
import os
if not os.path.exists("tmp/config.yaml"):
raise RuntimeError("config.yaml does not exist")
config=yaml.load(open("tmp/config.yaml").read(),
Loader=yaml.FullLoader)
print (authorize(config))
except RuntimeError as error:
print ("Error: %s" % str(error))
pyyaml
requests
requests_oauthlib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment