So currently I have in place a system using Flask running on my localhost:8080 to add 1 song at a time to a public Spotify playlist. Unfortunately how I have implemented this it requires a browser to add a song. What I want to be able to do is URLLIB or possibly the REQUESTS library to do this without a browser. I have been unsuccessful in my attempts to do this bot URLLIB and REQUESTS only see the first page of my local host it is never redirected to my call back in the code that I linked below.
My Implementation
How would I go about implemented a non browser interface to add a song to a playlist? (Mind you this is python 3)
In order to add a song to a playlist, you need the playlist's owner to grant access to your application, so you will need a web interface at some point to carry out this step.
It's important that you obtain the access token using the Authorization Code Flow since that's how you will get an access token and a refresh token. Use that refresh token in your app to obtain access tokens without having the user to re-authorize your app.
So in brief:
Implement a web site that uses the Authorization Code. A user logs in and you obtain an access token and refresh token. Using the refresh token you will be able to generate access tokens without the user having to input their credentials.
Take the refresh token and include it in your script. Before making the request to add a track, obtain a fresh access token using the refresh token.
It's a bit cumbersome but that's the only way to use OAuth2 without exposing the user's username+password to an app.
Related
I am trying to build an python application for my server to run 24 hours and overwrite a file in dropbox every minute. When I built this application it stopped working after an hours for new token. I can't awake 24 hour to add new token every token. I just want a way that help me in doing setup of this. With dropbox there is no option to remove short length expire from token. Please keep it simple to underatnd easily dropbox documentation is hard for me to understand.
I just want a solution for this problem. I tried refresh token but it also required user interaction so no use.
Using refresh tokens is the right solution here. Just like with Dropbox access tokens, manual user interaction is required initially to get a Dropbox refresh token, but once the app has a refresh token it can store and re-use it repeatedly without further manual user interaction.
For reference, Dropbox is in the process of switching to only issuing short-lived access tokens (and optional refresh tokens) instead of long-lived access tokens. You can find more information on this migration here.
Apps can still get long-term access by requesting "offline" access though, in which case the app receives a "refresh token" that can be used to retrieve new short-lived access tokens as needed, without further manual user intervention. You can find more information in the OAuth Guide and authorization documentation.
You can find examples of using the OAuth app authorization flow in the Dropbox Python SDK here.
I've created a simple Python program using Spotipy that shows some recommended tracks based on the tracks downloaded in the user device. But I'm having some trouble on making the program user-friendly.
First of all, is there any problem by sharing my Client ID and my Client Secret with the user by, for example, uploading my code in GitHub? Can I use Redirect URI as being http://localhost/ or should I create a website for my program for securing purposes? In Username field, it should be the username of the account to be analyzed or it can be anything, like "Brian Rogers"?
In the authentication part, it shows the user in Python console the following message:
User authentication requires interaction with your
web browser. Once you enter your credentials and
give authorization, you will be redirected to
a url. Paste that url you were directed to to
complete the authorization.
Opening https://... in your browser
Enter the URL you were redirected to:
My question is: since I'm managing to use Tkinter, how can I redirect the input from the Tkinter input box to the Python console?
Finally, how long does the authentication token take to expire? And if so, how to renew it (if possible, so that only the user enters when they run the program for the first time)?
Thanks in advance for the patient!
I'll address all your questions one by one.
is there any problem by sharing my Client ID and my Client Secret with the user by, for example, uploading my code in GitHub?
One should always avoid putting personal credentials in the source. If someone misuses your credentials, you'll be the one who will be held responsible because they are YOUR credentials. In any case, the only havoc I can imagine one could cause is to spam requests to Spotify's API which I believe Spotify's API already has protections and will drop further requests if it detects request spam. I've had and seen some projects put their Spotify and YouTube API credentials by creating special accounts for generating API credentials for their projects, in their source code and push to GitHub to make the tool easier to setup for use.
Can I use Redirect URI as being http://localhost/ or should I create a website for my program for securing purposes? In Username field, it should be the username of the account to be analyzed or it can be anything, like "Brian Rogers"?
As you're only searching for relevant tracks on Spotify, I believe you probably don't need to access the personal information of the Spotify user whose credentials you are using. If so, you can avoid both passing the username and verifying the redirect URI, by using oauth2.SpotifyClientCredentials to authorize yourself:
import spotipy
import spotipy.oauth2 as oauth2
credentials = oauth2.SpotifyClientCredentials(
client_id=client_id,
client_secret=client_secret)
token = credentials.get_access_token()
# This won't prompt for verification of Redirect URI
sp = spotipy.Spotify(auth=token)
My question is: since I'm managing to use Tkinter, how can I redirect the input from the Tkinter input box to the Python console?
You won't need to, if you use oauth2.SpotifyClientCredentials as mentioned above.
Finally, how long does the authentication token take to expire? And if so, how to renew it (if possible, so that only the user enters when they run the program for the first time)?
As of writing this, the token stays valid for exactly one hour. You can confirm by checking the value of credentials.token_info["expires_in"] which displays the time in seconds.
Also, spotipy raises spotipy.client.SpotifyException when a dependent method has been called but the token has already expired. So, you could catch this exception and overwrite your previous spotipy.client.Spotify instance with a new one. At the minimal you would do something similar to this:
import spotipy
import spotipy.oauth2 as oauth2
def authenticate_calls():
credentials = oauth2.SpotifyClientCredentials(
client_id=client_id,
client_secret=client_secret,
)
token = credentials.get_access_token()
sp = spotipy.Spotify(auth=token)
return sp
sp = authenticate_calls()
try:
do_something_that_needs_authentication(sp)
except spotipy.client.SpotifyException:
sp = authenticate_calls()
do_something_that_needs_authentication(sp)
You could also create a decorator function which would refresh the token if expired and decorate your functions with it!
I am developing an app that creates a public Spotify playlist for a user who has given proper authorization to do so.
I am using Flask and Python requests library to accomplish this, but after I've sent a few consecutive POST requests to get an access token from Spotify (using authorization code obtained from previous logic), it begins to fail. I am referring to Step 4 of Authorization Code Flow from this link: https://developer.spotify.com/web-api/authorization-guide/#authorization_code_flow
I know the authorization code is valid, because it doesn't fail for the first few times I run the request (maybe 5-10 times).
When I print the response from the POST I get the following:
{'error_description': 'Authorization code expired', 'error': 'invalid_grant'}
I assume I am not using the authorization code fast enough to get an access token (after repeatedly failing on code logic before the access token POST request, I guess?) but how am I supposed to reset and refresh the authorization code so I can keep making requests repeatedly? Any info on how long I am disabled and generally good programming practice to avoid this scenario?
When you use the authorization code to get your access token, you will also get a refresh token back in the same message. Use that refresh token to request new access tokens, when the access tokens expire.
How to use the refresh token is written on the same page you linked to, just a bit further down: https://developer.spotify.com/web-api/authorization-guide/#request-access-token-from-refresh-token
I agree that this is not the easiest to understand, but there are good reasons for all these things. It is also a standard called OAuth2, which many websites use to let users authorize apps to access their data, so it is useful in a lot of places.
In this specific case: "why do I need a refresh token to get an access token, I already have an authorization code to get an access token?", it is because the authorization code has leaked to the outside because it was returned to you via the user's browser.
An authorization code is obtained when the user grants permission for the third-party application (the Client). As per OAuth's 2.0 specification the authorization code must be used once and it's recommended that it have a maximum lifetime of 10 minutes to mitigate security flaws.
Read more about authorization code here:
https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2
On the other hand, instead of boring the user to go through all the OAuth 2.0 dance again (to authenticate and to grant permissions), the server side of Client application can use Refresh Tokens to ask for a new token when it's expired.
More about refresh tokens can be found at section 10.4 of OAuth 2.0 spec.
https://www.rfc-editor.org/rfc/rfc6749#section-10.4
I am writing an app that is supposed to work with Google contacts.
So at some point I do the authentication with OAuth2:
token = OAuth2Token(client_id=client_info["client_id"],
client_secret=client_info["client_secret"],
scope=CLIENT_SCOPE,
user_agent=USER_AGENT)
# I open a webserver and browser until I retrieve the
# Auth code in a variable named "code"
token.get_access_token(code)
As of now, this flow starts every time the app accesses contatcs.
How do i make my application remember the authentication?
Does it have to do with refresh tokens, and if so, how does that works?
Yes, you should save the refresh token (depending on your system configuration) that is exchanged using the code..
Next time the script runs, it should look for the refresh token first and should try to use it. If it doesn't find it or the refresh token doesn't work, it should try to get the new code.
I'm working on converting a Python script using the Google gdata API client + user/pass authentication to something more suitable for production (an API key). I am pretty frustrated with the muddled state of their documentation on authentication. I admittedly don't have a great grasp of OAuth2, but it seems like it's way more complicated for my usage case, which is: Hit Google Analytics every 24 hours to get the X most popular articles on our site.
In this scenario, we're not dealing with modifying someone's personal data, and all activity is centered on one account. It doesn't seem like OAuth2 is worth the complexity for something so simple.
I see that on the Google API Console (https://code.google.com/apis/console/), I've registered there and notice that there's a "Simple API Access" section with one key beneath the "Client ID for web applications" (which appears to be OAuth2). There's also the Google domain update page, https://www.google.com/accounts/UpdateDomain, but that appears to be OAuth related.
Is there any way to use this Simple API Access key (not OAuth) for retrieving analytics data with the Python gdata client, and if so, does anyone have any authentication examples? I already have the data retrieval stuff working once authenticated, but I'm using the user/pass approach, which is not appropriate for production.
Greg,
If you are already using the library gdata-python-client, this is relatively easy to do if you are the only user that your application will be authorizing.
The general mechanisms were detailed in a blog post in September, 2011, but I'll describe them here for completeness.
Part 1: Go to the APIs console and start a new project.
Part 2: From the project, go to "Services" and enable "Analytics API"
Part 3: From the project, go to "API Access" and click "Create an OAuth 2.0 client ID..." (you'll need to provide a product name, though the value you provide won't matter). When asked for the application type, select "Installed Application" and then "Create client ID". Since you will be the only user, you will only need one refresh token, and you can get this by authorizing from a desktop application a single time.
Part 4: Get your client id and client secret from the APIs console and then create an empty token:
import gdata.gauth
CLIENT_ID = 'id-from-apis-console'
CLIENT_SECRET = 'secret-from-apis-console'
SCOPE = 'https://www.google.com/analytics/feeds/' # Default scope for analytics
token = gdata.gauth.OAuth2Token(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=SCOPE,
user_agent='application-name-goes-here')
I got the scope from GData FAQ, though I'm not sure if it is correct.
Part 5: Use the token to create authorization URL for you to visit:
url = token.generate_authorize_url(redirect_uri='urn:ietf:wg:oauth:2.0:oob')
Since your application is an "Installed Application", your redirect URI is the default 'urn:ietf:wg:oauth:2.0:oob'. (Also note, the blog post had a typo and used the keyword argument redirect_url.)
Part 6: Visit the url and authorize your application to make requests on behalf of your account. After authorizing, you'll be redirected to a page with a code on it. This code will be used to exchange for an access token and a long-lived refresh token. The code has a life of 10 minutes and the access token has a life of an hour. The refresh token will allow you to get new access tokens for signing requests in perpetuity (or until you revoke the permission from your account).
Part 7: Use the code to get an access token:
code = 'random-string-from-redirected-page'
token.get_access_token(code) # This returns the token, but also changes the state
This again differs slightly from the blog post, because we are using an installed application.
Part 8: With the token you can now make all requests you want to make to the analytics client:
import gdata.analytics.client
client = gdata.analytics.client.AnalyticsClient()
token.authorize(client)
This is the big money right here. When an access token expires, the API requests signed with that token are rejected. However, by authorizing the client as above, when the said requests fail, the token attempts to use the refresh token to obtain a new access token. If it successfully obtains a new access token, the client resends the original API request, signed with the new access token.
I don't know anything about the Analytics API so I won't provide any more details there.
Future Use Note 1: Saving information for future use. You can re-use this from different places and after this use very easily. There are methods called token_to_blob and token_from_blob provided by the library that allow turning a token into a string and converting out of a string:
saved_blob_string = gdata.gauth.token_to_blob(token)
Once you have done this, you can store the string in a file and kill your running Python process. When you'd like to use it again:
saved_blob_string = retrieve_string_from_file() # You'll need to implement this
token = gdata.gauth.token_from_blob(saved_blob_string)
Future Use Note 2: This token will be able to be used to authorize a client and perform all your magic again and again, so long as you have the refresh token around. If for some reason you would like to get an access token again without calling token.generate_authorize_url, you'll need to manually set this on the object:
token.redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
Future Use Note 3: Also, if you lose your refresh token and would like to get another one without having to go to the browser to revoke the original, you can use the approval_prompt parameter to get a new refresh token by visiting the url generated by:
url = token.generate_authorize_url(
redirect_uri='urn:ietf:wg:oauth:2.0:oob',
approval_prompt='force')