Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Completing Spotify Authorization Code Flow via desktop application without using browser

Working on a small app that takes a Spotify track URL submitted by a user in a messaging application and adds it to a public Spotify playlist. The app is running with the help of spotipy python on a Heroku site (so I have a valid /callback) and listens for the user posting a track URL.

When I run the app through command line, I use util.prompt_for_user_token. A browser opens, I move through the auth flow successfully, and I copy-paste the provided callback URL back into terminal.

When I run this app and attempt to add a track on the messaging application, it does not open a browser for the user to authenticate, so the auth flow never completes.

Any advice on how to handle this? Can I auth once via terminal, capture the code/token and then handle the refreshing process so that the end-user never has to authenticate?

P.S. can't add the tag "spotipy" yet but surprised it was not already available

like image 965
Mitch Heard Avatar asked Dec 29 '15 22:12

Mitch Heard


2 Answers

Unfortunately, the spotipy util function only returns the access_token, not the all-important refresh_token. The access_token will expire after a limited amount of time. At that point, you'll need to create a new access_token using a refresh_token.

I did not see any public functions in spotipy that allow you to grab the refresh_token. However, you can always create a new access_token with the following components:

  • Your Spotify client id (found on your app page)
  • Your Spotify client secret (found on your app page)
  • Your Spotify refresh token - See here for a way to get that ONCE - https://developer.spotify.com/web-api/tutorial/

Word to the wise, when debugging I requested a new access_token using POSTMAN to POST to https://accounts.spotify.com/api/token - it only worked after specifying in the headers

  • 'Content-Type': 'application/x-www-form-urlencoded'
like image 67
louhow Avatar answered Oct 16 '22 18:10

louhow


I once ran into a similar issue with Google's Calendar API. The app was pretty low-importance so I botched a solution together by running through the auth locally in my browser, finding the response token, and manually copying it over into an environment variable on Heroku. The downside of course was that tokens are set to auto-expire (I believe Google Calendar's was set to 30 days), so periodically the app stopped working and I had to run through the auth flow and copy the key over again. There might be a way to automate that.

Good luck!

like image 45
grokpot Avatar answered Oct 16 '22 18:10

grokpot