spotipy-dev / spotipy

A light weight Python library for the Spotify Web API
http://spotipy.readthedocs.org
MIT License
5.01k stars 956 forks source link

User Authorization in Cloud Functions #1031

Closed Basti110 closed 4 months ago

Basti110 commented 1 year ago

Hey,

is it somehow possible to authorize a cloud function to add new songs to my private playlist, at any time without user interaction? I can not use bowser login with redirection urls in the cloud or at least I do not know how to use them there. Is there a direct way to log into my Spotify account via the API? The client credentials flow works in the cloud, but I can't use it to access my account. It always says "This request requires user authentication".

Thank you! Sebastian

deanja commented 11 months ago

I'm trying to get my head around this too.

First I can confirm that Spotify user data can't be accessed with Client Credentials flow. Instead I used the Authorization Code flow - https://developer.spotify.com/documentation/web-api/tutorials/code-flow.

For your cloud function solution it might work like this:

  1. Interact manually* with Spotify browser authentication page and the redirect_uri to complete steps 1 and 2 in the Authorization Code flow, at which point you'll have an access token and a refresh token, which can be used unattended, but will expire.
  2. make the refresh token persistently available to your cloud function - via environment variable, aws dynamodb etc
  3. trigger your cloud function to add songs to your playlist as normal. If it runs less frequently than once an hour, it can use the refresh token to get a new access token on each run. If multiple times in an hour it might cache the access token between runs and only use the refresh token once per hour.

That oAuth2 refresh token should be valid at least until redeemed for an access token, and possibly indefinitely until the user revokes access by your app in Spotify.

You could write a web app or similar to do step 1, to guide user through the Spotify authentication and save the tokens where your cloud function can access them.

Nico-VC commented 5 months ago

Yes. The key is running the authorization code flow once to get the .cache file for that user and have that accessible to read everytime your function runs.

See https://stackoverflow.com/questions/48883731/refresh-token-spotipy

dieser-niko commented 5 months ago

@Basti110 is your issue resolved or do you still need help and/or other solutions to your problem?

dieser-niko commented 4 months ago

Closing as there is no activity or reply from the author.