Skip to content

Instantly share code, notes, and snippets.

@rfinnie
Created April 23, 2023 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rfinnie/618298d5567e6e2eeebaeae072199680 to your computer and use it in GitHub Desktop.
Save rfinnie/618298d5567e6e2eeebaeae072199680 to your computer and use it in GitHub Desktop.
# Mastodon OAuth 2.0 API authentication
# Ryan Finnie <ryan@finnie.org>
# When you create an application through the Development section of Mastodon,
# it gives you three items: client key, client secret and access token (the
# latter which can be regenerated in the UI). You can use the access token
# directly, sending the header "Authorization: Bearer ${ACCESS_TOKEN}" with
# API requests, or you may initiate an OAuth 2.0 workflow to generate a
# per-session token.
import logging
import shlex
from requests_oauthlib import OAuth2Session
BASE_URL = "https://example.mastodon.com"
CLIENT_KEY = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
CLIENT_SECRET = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
TEST_URL = "{}/api/v1/apps/verify_credentials".format(BASE_URL)
OAUTH_AUTH_URL = "{}/oauth/authorize".format(BASE_URL)
OAUTH_TOKEN_URL = "{}/oauth/token".format(BASE_URL)
logging.basicConfig(level=logging.DEBUG)
def initial_auth():
session = OAuth2Session(CLIENT_KEY, redirect_uri="urn:ietf:wg:oauth:2.0:oob")
authorization_url, _ = session.authorization_url(OAUTH_AUTH_URL)
logging.info("Authorization URL: {}".format(authorization_url))
auth_code = input("Authorization code: ").strip()
token = session.fetch_token(
OAUTH_TOKEN_URL, client_secret=CLIENT_SECRET, code=auth_code
)
r = session.get(TEST_URL)
logging.info(r.json())
return token
def subsequent_auth(token):
session = OAuth2Session(CLIENT_KEY, token=token)
r = session.get(TEST_URL)
logging.info(r.json())
token = initial_auth()
logging.info(token)
subsequent_auth(token)
logging.info(
shlex.join(
[
"curl",
"-v",
"-H",
"Authorization: {} {}".format(token["token_type"], token["access_token"]),
TEST_URL,
]
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment