Toying around with Soundclouds SDK for Python with an impact of TKinter as GUI. Now I want to generate a access token for each user so that I could access more API-endpoints.
I have created an applicaton in Soundclouds Developer portal with a link to my callback.
There is nothing corresponding to generating a access token for an desktop application. Only for server-side application. I tried this code below:
import soundcloud
# create client object with app credentials
client = soundcloud.Client(client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
redirect_uri='REDIRECT_URL')
# redirect user to authorize URL
redirect client.authorize_url()
I have set my keys, and redirect_uri as the callback on my webserver. When I run my python file from the terminal, I get this:
File "token.py", line 9
redirect client.authorize_url()
^
SyntaxError: invalid syntax
Using Python 2.7.5+
What is causing this? I want to generete my access token and print in later on.
The solution might be that I need to create an instance of an web browser window, make the user accept the app using Soundcloud connect. The I grab the url and sort out the "code" in the url. Exchanges the code against an access-token and stores it inside a text-file. So that I could grab it later on.
A simple way of obtaining an access token is by first authenticating via the User Credentials flow, which exchanges your username and password for an access token:
client = soundcloud.Client(client_id = 'CLIENT_ID',
client_secret = 'CLIENT_SECRET',
username = 'USERNAME',
password = 'PASSWORD')
print client.access_token
try:
redirect(client.authorize_url())
Related
I made a script that works perfectly when it runs locally but isn't able to authenticate in my Azure Functions app. At first, I thought it was because it couldn't read the .cache file.
After looking at the logs it's because it can't open a browser window to create the authentication token. I'm fairly new to Azure functions so I'm not sure how I can enable opening a browser if that's even possible.
I looked into the oauth2.py file in spotipy and found it's optional to open the browser but instead, the console asks for the redirected URL. Is there a way for me to get the redirected URL and enter it into the console instead?
Here's my code:
def create_playlist(cred):
"""Creates the playlist for Discover weekly to be copied to"""
# Gain authorization to create playlist
logging.info('Authenticating spotify secrets to create new playlist...')
# spotipy.CacheFileHandler(cache_path='')
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=cred[0],
client_secret=cred[1],
redirect_uri=cred[2],
scope='playlist-modify-private',
open_browser=False,
))
# Get returned list from get_playlist_info function
logging.info('Determining playlist descriptors...')
info = get_playlist_info()
# New playlist for Discover Weekly
logging.info('Creating new playlist...')
new_playlist = sp.user_playlist_create(user=cred[4],
name=info[0],
public=False,
collaborative=False,
description=info[1])
logging.info('Returning new playlist.')
return new_playlist
In Redirect URIs you enters one or more addresses which you want to whitelist with Spotify. And this URI enables the Spotify authentication service to automatically re-launch your app every time the user logs in.
You can set your Redirect URL by navigating to your Spotify developer dashboard and open the project you are working on. Then click "edit settings" and look for the redirect URIs field and put your redirect URI in the field and lastly save it.
The Authorization Code Flow needs you to add a redirect URI to your application at My Dashboard. The redirect_uri argument or SPOTIPY_REDIRECT_URI environment variable must match the redirect URI added to your application in your Dashboard.
Following are some examples that you can use as redirect URIs.
http://example.com, http://localhost or http://127.0.0.1:9090
The correct way in which you should authenticate yourself is shown in the code snippet below.
token = util.prompt_for_user_token(
username=USERNAME,
scope=SCOPE,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI)
You should also export your redirect_uri, client ID, and secret before running your script and trying to authenticate. If you don't pass the values directly to the util.prompt_for_user_token function, it will read them from the environment.
Try running these in your terminal before running your script.
export SPOTIPY_CLIENT_ID="YOUR CLIENT ID"
export SPOTIPY_CLIENT_SECRET="YOUR CLIENT SECRET"
export SPOTIPY_REDIRECT_URI='http://localhost/'
For more information you can read this Authorization Code Flow document for Spotipy.
I am attempting to create a login tool for my work which will log me in to various sites that log me out after 3 minutes of inactivity. I have gotten it to work on a number of sites, but none have required an MFA token. I currently use Google Authenticator but can also use an email, or a couple different options. How would I go about getting that code programmatically to make my login process much faster? I am using Selenium as I need to use the webpage after I log into it. Here is my code thus far:
def loginsys():
driver = webdriver.Chrome('C:/path/to/chromedriver.exe')
driver.get('https://www.specifiedurl.com/login')
username = driver.find_element_by_id('txtUsername')
password = driver.find_element_by_id('txtPassword')
username.send_keys("myusername")
password.send_keys("mypassword")
driver.find_element_by_name('btnLogin').click()
### This is where I need to do MFA as it will not pull the next page without it
driver.get('https://www.specifiedurl.com/page/after/login')
Thoughts? (Obviously, this is not the url, nor is that my actual username or password)
Check the pyotp library. You can get the MFA key associated with google authentication as shown below.
from pyotp import *
# get the token from google authentication
totp = TOTP("your 16 character security token goes here")
token = totp.now()
print (token)
# now you can use token in your script
I have a python api which accepts email and password from a login webpage. This email and password is used to login to azure ad and in response we get a access token which is valid for 1hr. Below is the sample python code:
context = adal.AuthenticationContext(config_data['AUTHORITY_HOST_URL'] + '/' + config_data['TENANT'], validate_authority="cceaddik-1q7c5-997ad-6453-sduf9347asit8" != 'adfs')
token = context.acquire_token_with_username_password(config_data['RESOURCE'], email, password, config_data['CLIENT_ID'])
print(token['accessToken'])
Normally this token generated for a user should be valid for 1hr and if same user is logging again within the same 1hr, it should get the same access token. But what I have noticed is that, each time we login, we are getting different access token. Why is this happening. Can anyone please throw some lights on it. Thanks.
You will always get a new token when you call Azure AD. It does not cache tokens there.
A token is valid for one hour from the time you requested the token.
As a side note, handling passwords is a bad idea in general.
It would be much better to use one of the interactive login flows like authorization code flow.
You cannot enable MFA for users for example, as the login would fail.
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 am trying to write a script on Python that fetches my friend list from facebook. To fetch data, I need to get the access token. I am using requests_oauthlib package to achieve the same. Since I am not writing a web application, I have not used local webserver(no redirect url). I choose to use Resource owner password credentials grant type. I am getting error.
This is my code:
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import LegacyApplicationClient
FACEBOOK_APP_ID = '**********'
FACEBOOK_APP_SECRET = '*********'
username = 'Aman Mittal'
password = '****'
token_url = "https://graph.facebook.com/oauth/access_token"
oauth = OAuth2Session(client=LegacyApplicationClient(client_id=FACEBOOK_APP_ID))
oauth_access_token = oauth.fetch_token(token_url, client_secret=FACEBOOK_APP_SECRET,username=username, password=password, client_id=FACEBOOK_APP_ID)
When I run the script, it shows error - 'Missing access token parameter'
I went through traceback and realized that access token received is this:
{"error":{"message":"Missing redirect_uri parameter.","type":"OAuthException","code":191,"fbtrace_id":"CUSmQKT8YGb"}}
First of all, I don't understand while using Legacy Application client(Resource Owner password credentials grant type ), why do I need redirect uri?
If I do choose to start a webserver alongside using web.py or something else. How do I register it on Facebook? or Do I even need to?
PS. I am new to both Python and posting on Stack Overflow. Please try to explain with details and forgive me if I have committed any stupid mistake.
Facebook does not support the OAuth 2.0 Resource Owner Password Credentials grant type.