Coding on VScode and on Windows 11
Hi everybody. I was very excited when I discovered the potential of the Spotify's API. However I'm still struggling with the authentication step. I'm trying to connect to my own spotify account so far.
Bellow is the basic code I was trying to run:
`
import spotipy
import spotipy.util as util
my_username = "47tol*******************h7en8"
my_scope = "user-library-read"
token =util.prompt_for_user_token(username = my_username,
scope = my_scope,
client_id = "5e5197d3dd2c4a52bdad0bead149c334",
client_secret = "7t********************14",
redirect_uri = "http://797096755318371914146942828329574")
sp = spotipy.Spotify(auth = token)
user = sp.current_user()
print(user["display_name"])
print(user["followers"]["total"])
`
This kind of works and properly open the web browser (chrome) but the spotify logging page shows "accounts.spotify.com sent an invalid response"
enter image description here
I have tried everything but can't get by this issue.
Right before, on the same computer, I have run this code
`
import spotipy
from spotipy.oauth2 import SpotifyOAuth
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="5e5197d3dd2c4a52bdad0bead149c334",
client_secret="7t********************14",
redirect_uri="http://797096755318371914146942828329574",
scope="user-library-read"))
user = sp.current_user()
print(user['display_name'])
print(user['followers']['total'])
`
It opened the browser, I confirmed the connexion (my spotify account is connected on chrome), then the following code run smoothly.
I read maybe the connexion token has been saved on my computer so maybe I can't connect twice the same account to my App through the API??? Anyway I've tried :
`
os.remove(f".cache-{my_username}")
`
But it couldn't be able to find the file so I guess the problem is not that the token was already stored on my computer.
I then tried to run this code on another computer. The chrome page to connect to spotify opened well, I click on connect. Then the "accounts.spotify.com sent an invalid response" show up again and I'm back at the same point.
I you have some hint I'll be glad to read you. Many thanks
PS: The user name is mine. It is shown like this when on my spotify account (the one to listen to music) i click on "copy link to profile". I think it's because I create my account through a facebook account. I have also tried my "proper" spotify username but doesn't work neither.
Related
I have a basic understanding of auth2 and believe I am using the right protocol version (Oauth2 user context) to allow user login.
But I keep getting errors, probably because I'm missing knowledge and not understand some concepts.
I'm creating a basic web app with Tweepy.
I'm able to print and check the auth_url which when I paste in my browser, directs me as a user to authorize the app on twitter (but I get stuck on the redirect uri and in general get the error logged below):
Codebase:
import tweepy
import config
oauth2_user_handler = tweepy.OAuth2UserHandler(
client_id="",
redirect_uri="http://127.0.0.1:5000",
scope=["tweet.write"],
client_secret=""
)
auth_url = oauth2_user_handler.get_authorization_url()
access_token = oauth2_user_handler.fetch_token(f"{auth_url}")
client = tweepy.Client(f"{auth_url}")
The error message im getting:
"""
in parse_authorization_code_response
raise MissingCodeError("Missing code parameter in response.")
oauthlib.oauth2.rfc6749.errors.MissingCodeError: (missing_code) Missing code parameter in response.
"""
A few side notes I have:
What website URL do I put in my app settings? (Do I need to spin up a server and get the URL from that dashboard?) How is the website URL related to the callback URI and how do they differ? this is my first time working with authentication & Twitter API.
I am trying to build a most basic python app that uses OAuth2 to log into GitHub and fetch from there my username - using requests-oauthlib (this one: https://requests-oauthlib.readthedocs.io/en/latest/examples/github.html).
Here is the code from there:
from requests_oauthlib import OAuth2Session
from flask.json import jsonify
client_id = <my GitHub id>
client_secret = <my GitHub secret>
authorization_base_url = 'https://github.com/login/oauth/authorize'
token_url = 'https://github.com/login/oauth/access_token'
github = OAuth2Session(client_id)
authorization_url, state = github.authorization_url(authorization_base_url)
print('Please go here and authorize,', authorization_url)
redirect_response = input('Paste the full redirect URL here:')
github.fetch_token(token_url, client_secret=client_secret,
authorization_response=redirect_response)
r = github.get('https://api.github.com/user')
print(r.content)
If I add the generated link to the browser, press enter, the url will change like a charm into a localhost:8080 (the callback url I provided in GitHub) with a code and state param. If I input it in my python code, I am able to fetch the GitHub data.
My question is, is there any way to automatize this? Like, skipping the user interaction and simply ask for the credentials in GitHub then print my data in the console?
Thanks
You are using the web application flow. For your purpose, it would be better to use the Device Flow.
Basically, the user needs to add a code that you will provide on a GitHub page input. And since you are using this as a simple app you could do that in a lower level and use the simple GET and POSTS requests together with requests
I am trying to use a Python script to fetch my shared calendars in outlook. I am a first year computer science major and beginner. I thought it would be nice to have all my calendar events print to the terminal and I thought this little activity would benefit me. However, I get an invalid scope value error in my browser, after pasting the sign-in portal link into chrome. I have added all the permissions and platform configs to Azure that I thought I needed to? What am I missing?
Error in browser:
https://login.microsoftonline.com/common/oauth2/nativeclient?error=invalid_scope&error_description=The%20provided%20value%20for%20the%20input%20parameter%20%27scope%27%20is%20not%20valid.%20The%20scope%20%27Calendars.Read.Shared%27%20is%20not%20valid.&state=iC6gDfcX1C7BCPfsrvdHpp4a7kzcRr
Terminal Output:
Visit the following url to give consent:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?response_type=code&client_id=844ecf49-96c1-422d-a611-b7bad4882745&redirect_uri=https%3A%2F%2Flogin.microsoftonline.com%2Fcommon%2Foauth2%2Fnativeclient&scope=Calendars.Read.Shared&state=iC6gDfcX1C7BCPfsrvdHpp4a7kzcRr&access_type=offline
Paste the authenticated url here:
Here's my code:
from O365 import Account, MSGraphProtocol
CLIENT_ID = '844ecf49-96c1-422d-a611-b7bad4882745'
SECRET_ID = 'q~-n~w9_kTb6mTIrbmcA2-139rqiSph4n_'
SCOPE = ["Calendars.Read.Shared"]
credentials = (CLIENT_ID, SECRET_ID)
protocol = MSGraphProtocol()
account = Account(credentials, protocol=protocol)
if account.authenticate(scopes=SCOPE):
print("Authenticated!")
schedule = account.schedule()
calendar = schedule.get_default_calendar()
events = calendar.get_events(include_recurring=False)
for event in events:
print(event)
permissions in Azure image
Platform configurations in Azure
Anyone know if this is possible?
I just want to automate dropping some documents into my onedrive for business account.
I tried
import onedrivesdk
from onedrivesdk.helpers import GetAuthCodeServer
from onedrivesdk.helpers.resource_discovery import ResourceDiscoveryRequest
redirect_uri = 'http://localhost:8080'
client_id = 'appid'
client_secret = 'mysecret'
discovery_uri = 'https://api.office.com/discovery/'
auth_server_url='https://login.live.com/oauth20_authorize.srf?scope=wl.skydrive_update'
#auth_server_url='https://login.microsoftonline.com/common/oauth2/authorize',
auth_token_url='https://login.microsoftonline.com/common/oauth2/token'
http = onedrivesdk.HttpProvider()
auth = onedrivesdk.AuthProvider(http,
client_id,
auth_server_url=auth_server_url,
auth_token_url=auth_token_url)
auth_url = auth.get_auth_url(redirect_uri)
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)
auth.authenticate(code, redirect_uri, client_secret, resource=resource)
# If you have access to more than one service, you'll need to decide
# which ServiceInfo to use instead of just using the first one, as below.
service_info = ResourceDiscoveryRequest().get_service_info(auth.access_token)[0]
auth.redeem_refresh_token(service_info.service_resource_id)
client = onedrivesdk.OneDriveClient(service_info.service_resource_id + '/_api/v2.0/', auth, http)
I registered an APP and got a secret and id. But when I ran this I got scope is invalid errors. Plus it tries to launch a webpage which isn't great for a command line kinda environment. I think this SDK might be outdated as well because originally this script had login.microsoftonline, but that wasn't reachable so I changed it to login.live.com.
I wrote this sample code you posted. You replaced the auth_server_URLwith the authentication URL for Microsoft Account authentication, which can only be used to access OneDrive (the consumer product). You need to continue using the login.microsoftonline.com URL to log into your OneDrive for Business account.
You are correct that this pops up a dialog. However, you can write a little supporting code so that only happens the first time you log into a particular app. Follow these steps (assuming you are using the default implementation of AuthProvider:
Use the sample code above up through the line auth.redeem_refresh_token()
The AuthProvider will now have a Session object, which caches the credentials of the current user and session. Use AuthProvider.save_session() to save the credentials for later.
Next time you start your app, use AuthProvider.load_session() and AuthProvider.refresh_token() to retrieve the previous session and refresh the auth token. This will all be headless.
Take note that the default implementation of SessionBase (found here) uses Pickle and is not safe for product use. Make sure to create a new implementation of Session if you intend to deploy this app to other users.
Onerive's website shows "Not Yet" on "OneDrive SDK for Python" to "OneDrive for Business"
https://dev.onedrive.com/SDKs.htm
The github sample codes did not work for me either, it tried to popup a window of authentication, but IE can not find the address:
http://('https//login.microsoftonline.com/common/oauth2/authorize',)?redirect_uri=http%3A%2F%2Flocalhost%3A8080&client_id=034xxxx9-9xx8-4xxf-bexx-1bc5xxxxbd0c&response_type=code
or removed all the "-" in client id
http://('https//login.microsoftonline.com/common/oauth2/authorize',)?redirect_uri=http%3A%2F%2Flocalhost%3A8080&client_id=034xxxx99xx84xxfbexx1bc5xxxxbd0c&response_type=code
Either way, I got the same result, IE did not show the popup with a line "This page can’t be displayed"
I installed Django Facebook and I am using this method to post to a Page:
from open_facebook.api import OpenFacebook
graph = OpenFacebook("my_access_token")
graph.set('me/feed', message='hello world')
It's working on my local dev machine when I am logged in to my Facebook account. It stops working as soon as I sign out and I get this message:
OAuthException: Error validating access token: The session is invalid because the user logged out. (error code 190)
I got my access token from Graph API Explorer by passing /me/accounts
So the question, how do I make my code work on production when of course I'll not be logged in?
Please note that I'll only be posting to a Page that I own.
If you want to use 'me/feed' offline;
You can use the APP Access Token, once you've authorized the app and call USER_ID/feed to post.
Note: use user_id instead of me- me is only used when a user is in session, but you want to do the action after logout.
To get the app access token,
GET /oauth/access_token?
client_id={app-id}
&client_secret={app-secret}
&grant_type=client_credentials