Skip to content

Instantly share code, notes, and snippets.

@danvas
Last active November 28, 2023 20:20
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 danvas/b946bf676cd2f661db009e8e4c2c8394 to your computer and use it in GitHub Desktop.
Save danvas/b946bf676cd2f661db009e8e4c2c8394 to your computer and use it in GitHub Desktop.
Authorization code flow with PKCE

Python implementation of authorization code flow with PKCE for the Spotify Web API.

https://developer.spotify.com/documentation/web-api/tutorials/code-pkce-flow

Prerequisites:

  • Install authlib dependency
  • Create a Spotify app
  • Create an access token in your Spotify dashboard and make sure the redirect URI is set
  • Set environment variables:

SPOTIFY_REDIRECT_URI=http://localhost:80/callback

SPOTIFY_CLIENT_ID=<your-client-id>

See https://developer.spotify.com/documentation/web-api/tutorials/getting-started for more info.

from authlib.common.security import generate_token
from authlib.integrations.requests_client import OAuth2Session
from pprint import pprint
import logging
import os
import sys
# OAuth endpoints given in the Spotify API documentation
# https://developer.spotify.com/documentation/general/guides/authorization/code-flow/
# https://developer.spotify.com/documentation/general/guides/authorization/scopes/
SPOTIFY_AUTHORIZE_ENDPOINT = "https://accounts.spotify.com/authorize"
SPOTIFY_TOKEN_ENDPOINT = "https://accounts.spotify.com/api/token"
client_id = os.getenv('SPOTIFY_CLIENT_ID')
redirect_uri = os.getenv('SPOTIFY_REDIRECT_URI')
log = logging.getLogger('authlib')
log.addHandler(logging.StreamHandler(sys.stdout))
log.setLevel(logging.DEBUG)
def _spotify_auth_pkce_flow():
scope = ["user-read-email", "playlist-read-collaborative", "user-read-currently-playing"]
spotify = OAuth2Session(
client_id,
redirect_uri=redirect_uri,
scope=scope,
code_challenge_method="S256"
)
code_verifier = generate_token(128)
authorization_url, _ = spotify.create_authorization_url(
SPOTIFY_AUTHORIZE_ENDPOINT,
code_verifier=code_verifier
)
print('Please go here and authorize: ', authorization_url)
redirect_response = input('\n\nPaste the full redirect URL here: ')
token = spotify.fetch_token(
SPOTIFY_TOKEN_ENDPOINT,
authorization_response=redirect_response,
code_verifier=code_verifier,
)
pprint(token)
# Fetch a protected resource, i.e. user profile
r = spotify.get('https://api.spotify.com/v1/me')
pprint(r.json())
r = spotify.get('https://api.spotify.com/v1/me/player/currently-playing')
if r.status_code == 204:
print("No song playing")
return
pprint(r.json())
if __name__ == "__main__":
_spotify_auth_pkce_flow()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment