Redirect URI setting on Spotify developer API authorization - spotify

I'm trying to get information of my liked tracks on spotify thru spotity API
My local environment
Docker desktop for win container based on Ubuntu (on WSL2/Win11 PC)
with using spotipy library and in my local python code.
https://developer.spotify.com/documentation/web-api/reference/#/operations/get-users-saved-tracks
I have faced authorization error  on Redirect URI. in some cases.
I have known the Redirect URI value should be same both of 
in the setting on my app in dashboard and my code as redirect_uri.
I have been coding on my local dev env JupyterLab.
I 've tried many times.
I had set value in the redirect URI field  in some cases as follows
1)
"http://localhost:8888/callback"
==error message
OSError: [Errno 98] Address already in use
2)
http://example.com/callback
==error message
TypeError: can only concatenate str (not "NoneType") to str
This case 
my program console required to input redirect uri 2 times
just after I run my python code.
https://github.com/meowsa00/for_smri_qa_to_share/blob/main/spotify_backup4likedtracks.ipynb
-Question
What is the correct value that should be input to redirect URI?
Let me know what redirect URI I should input to be authorized.
someone who faced same error on the same environment of mine, 
Could you please let me know the solution? 

Related

When I use pycurl to execute a curl command, I get error 3 "illegal characters found in URL" but when pasting said URL in Chome, it can be resolved

Good day. I'm writing a python program that requests some posts from my Facebook page. To do so, Facebook offers a tool that they call "Graph API Explorer". Using something similar to a GET request, I can get anything that I want (granted that I have access and a valid token). I've come up with my own solution for the Graph API Explorer and that is generating my URLs. After generating a URL, I use pycurl to get a JSON object from Facebook that contains all of my data.
When I use pycurl, I get the following error:
pycurl.error: (3, 'Illegal characters found in URL')
but when printing said URL and pasting it to a browser, I got a valid response.
URL: https://graph.facebook.com/v7.0/me?fields=posts%7Bmessage%2Cfrom%7D&access_token=<and my access token which is valid>
my code looks like this:
def get_posts_curl(nodes=['posts'], fields=[['message', 'from']], token_file='Facebook/token.txt'):
curl = pycurl.Curl()
response = BytesIO()
token = get_token_from_file(token_file)
# constructing request.
url = parse_facebook_url_request(nodes, fields, token)
url = convert_to_curl(url)
print("---URL---: " + url)
# curl session and settings.
curl.setopt(curl.CAINFO, certifi.where())
curl.setopt(curl.URL, url)
curl.setopt(curl.WRITEDATA, response)
curl.perform()
curl.close()
return response.getvalue().decode('utf-8')
The error pops up at curl.perform()
Some info that might be relevant:
All was working great a while ago. After transferring my program from my workstation (that is running Windows 10) to my server (Ubuntu 18.04 Server) still, all was working fine and I placed that project to the side. Only now that error pops up and I haven't touched the project in a while.
It seems that the token is causing the issue. I've tried about 100 tokens and some cause the problem and some don't. Also, a fix that solved it all was using urllib3.unquote
from urllib.parse import unquote
...
url = unquote(url)

IDX21323 error and sometime looping in the URL in azure b2c

I am getting the error IDX21323 OpenIdConnectProtocolValidationContext.Nonce was null, OpenIdConnectProtocolValidatedIdToken.Paylocad.Nonce was not null.
https://testing.demo.com/message=IDX21323:%20RequireNonce%20is%20'[PII%20is%20hidden]'.%20OpenIdConnectProtocolValidationContext.Nonce%20was%20null,%20OpenIdConnectProtocol.ValidatedIdToken.Payload.Nonce%20was%20not%20null.%20The%20nonce%20cannot%20be%20validated.%20If%20you%20don't%20need%20to%20check%20the%20nonce,%20set%20OpenIdConnectProtocolValidator.RequireNonce%20to%20'false'.%20Note%20if%20a%20'nonce'%20is%20found%20it%20will%20be%20evaluated.
I checked in other SO links and found this issue is related to redirect URI mismatch like if you have one URL in the code but different one in AZure.
IDX21323 OpenIdConnectProtocolValidationContext.Nonce was null, OpenIdConnectProtocolValidatedIdToken.Paylocad.Nonce was not null
For me Redirect URI same for both i.e. in code and Azure. moreover I registered one application with two redirect URI (http://localhost:11111/ and https://testing.demo.com). so when I am running through local using localhost it's working fine but when I use https://testing.demo.com, I got IDX21323 error in my system, where as in different system its in a loop.
https://login.microsoftonline.com/{tenantID}/oauth2/authorize?client_id={client ID}&redirect_uri=https%3a%2f%2flogin.microsoftonline.com%2fte%{tenant ID}%2foauth2%2fauthresp&response_type=id_token&response_mode=form_post&nonce={nonce 1}state=StateProperties%3deyJTSUQiOiJ4LW1zLWNwaW0tcmM6qswsdwdY2OTAtNzlk
The above URL remains same but only the nonce got changed everytime.
So is it because I have kept two redirect URI for the same application. Do I need to create two different application one for localhost (Redirect URI - http://localhost:11111) and another for Dev (Redirect URI - https://testing.demo.com)
Your expertise matters.
Thanks!!
Its always recommended to use different application for development and production. Mainly from security and isolation point of view.
Your redirect_url seems to be wrong, its pointing to the tenant itself and hence in a loop. The redirect_uri below should be your app's reply url - http://localhost:11111 or https://testing.demo.com,
https://login.microsoftonline.com/{tenantID}/oauth2/authorize?client_id={client ID}&redirect_uri=http://localhost:11111/&response_type=id_token&response_mode=form_post&nonce={nonce 1}state=StateProperties%3deyJTSUQiOiJ4LW1zLWNwaW0tcmM6qswsdwdY2OTAtNzlk

Spotipy - Cannot log in to authenticate (Authorization Code Flow)

I am working with the Spotipy Python library to connect to the Spotify web API. I want to get access to my Spotify's user account via Authorization Code Flow. I am using Python 3.5, Spotipy 2.4.4, Google Chrome 55.0.2883.95 (64-bit) and Mac OS Sierra 10.12.2
First, I went to the Spotify Developer website to register the program to get a Client ID, a Client Secret key and enter a redirect URI (https://www.google.com) on my white-list.
Second, I set the environment variables from terminal:
export SPOTIPY_CLIENT_ID='my_spotify_client_id'
export SPOTIPY_CLIENT_SECRET='my_spotify_client_secret'
export SPOTIPY_REDIRECT_URI='https://www.google.com'
Then I try to run the example code typing 'python3.5 script.py my_username' from terminal. Here is the script:
import sys
import spotipy
import spotipy.util as util
scope = 'user-library-read'
if len(sys.argv) > 1:
username = sys.argv[1]
else:
print "Usage: %s username" % (sys.argv[0],)
sys.exit()
token = util.prompt_for_user_token(username, scope)
if token:
sp = spotipy.Spotify(auth=token)
results = sp.current_user_saved_tracks()
for item in results['items']:
track = item['track']
print track['name'] + ' - ' + track['artists'][0]['name']
else:
print "Can't get token for", username
When running this code, it takes me to a log in screen on my browser. I enter my Spotify's credential to grant access to my app. But when I finally click on 'log in' (or 'Iniciar sesión' in Spanish) nothing happens. I tried to log in with my Facebook account but it does not work either. It seems that I get a Bad Request every time that I click on 'log in'. Here is a capture of Chrome:
The process is incomplete because when trying to enter the redirect URI back on terminal I get another Bad Request:
raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request
I tried to restart my computer, clean my browser cookies, use another different browser but did not work. It seems that I am not the only one having this problem. Is it maybe a bug? Please, avoid answers like "read the documentation of the API going here". Thank you.
Solved it. In order to run the Authorization Code Flow example code provided in the Spotipy's documentation correctly, I specified the redirect URI in line 13 of the example script when calling util.prompt_for_user_token, even when I had done this previously when setting environment variables:
token = util.prompt_for_user_token(username, scope, redirect_uri = 'https://example.com/callback/')
Likewise, do not use https://www.google.com or similar web address as your redirect URI. Instead, try 'https://example.com/callback/' or 'http://localhost/' as suggested here. Do not forget that the redirected URL once you are logged in must have the word code included.
Cheers,

HTTP POST request from Android App denied on Domain but works using IP address‏

I'm trying to send a HTTP POST request to a PHP file on my web hosting server from my Android app.
That request contains the data from the app and is validated or saved on the server and then the PHP file sends a JSON response which is received by the Android device and the actions are taken accordingly like logging in or registering etc.
Now the problem that has arisen is that till now I didn't have a paid DOMAIN instead only a HOSTING service. That Hosting Service gave me a Server IP address to access the Index.php file I had uploaded.
So in my Android code I had written the url to be connected as http://10x.xxx.xx.xx/index.php/
and the request and response were working totally fine.
Now I have purchased a Domain name from Godaddy.com and I'm forwarding that domain name to the Server IP I had and when I open it in browser it's working perfectly fine. And so I changed the ip on which the request should be sent in my Android code to http://www.sampleurl.com/index.php/
This is my index.php file
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// get tag
$tag = $_POST['tag'];
//do other authorization stuff
}
else
echo "Access Denied";
Now the problem is when I'm using the Server Ip address to connect it goes into the if block and functions correctly. But when I use the Domain name it always returns Access Denied.
The Logcat shows:
03-18 02:59:08.780: E/JSON(30892): Access Deniedn
03-18 02:59:08.780: E/JSON Parser(30892): Error parsing data org.json.JSONException: Value Access of type java.lang.String cannot be converted to JSONObject
03-18 02:59:08.780: W/System.err(30892): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
Now I don't know how a letter 'n' is appended after 'Access denied' neither why the request is not being served correctly.
P.S. I have used forwarding instead of updating the NS at the domain. Can that possibly be causing the issue?
With the DNS being configured to forward, your post-request got lost. Check your server logs. You need to set it to be a type A record.

Using SSL with the python-instagram and localhost on sample-app.py

I plan on using the sample-app.py as a baseline of what I am building out and then expanding it from there. Just want to get comfortable with the instagram API and build out from there.
I am trying to use the sample-app.py provided with python-instagram. I have registered an application on instagrams website. I set it up using the default redirect uri from sample-app.py:
http://localhost:8515/oauth_callback .
I was able to authorize my instagram account to use the app, but when I click on any of the links, I get an error about the acccess-token.
When you look at the python command-line window that stays open, I get the following error:
"check_hostname needs a SSL context with either CERT_OPTIONAL or CERT_REQUIRED"
It appears that when the sample app is processing the lines below, it is trying to connect to instagram, but is not able to because SSL in local host is not set up properly. How do I set up SSL so i do not get the above error?
access_token, user_info = unauthenticated_api.exchange_code_for_access_token(code)
if not access_token:
return 'Could not get access token'
api = client.InstagramAPI(access_token=access_token)
request.session['access_token'] = access_token
print ("access token="+access_token)
There are a few steps to solve this problem (it appears that it is actually several problems in aggregate causing this issue):
use openssl to create a ssl certificate and save cert to the same location as your python script. Download open ssl here: http://slproweb.com/products/Win32OpenSSL.html
You need to tweak bottle so that it will support ssl. Do so by adding the following lines in run in class WSGIRefServer(ServerAdapter):
import ssl
srv.socket = ssl.wrap_socket (
srv.socket,
certfile='server.pem', # path to certificate
server_side=True)
There is a bug in python 3 and above(https://github.com/jcgregorio/httplib2/issues/173). I am using 3.4, so the bug could be fixed in 3.5. In the instagram/oauth2.py file, change all disable_ssl_certificate_validation=False to True.

Resources