Problem authorizing client with django-oAuth-toolkit Authorization Code flow - python

I have been following the django-oAuth-toolkit documentation. In the Authorization Code step, I have registered an application as shown in the screenshot.
But then the next step is given like this:
To start the Authorization code flow go to this URL which is the same as shown below:
http://127.0.0.1:8000/o/authorize/?response_type=code&client_id=vW1RcAl7Mb0d5gyHNQIAcH110lWoOW2BmWJIero8&redirect_uri=http://127.0.0.1:8000/noexist/callback
But when I replace my client id and ping that URL it redirects me to the following URL:
http://localhost:8000/noexist/callback?error=invalid_request&error_description=Code+challenge+required.
I have tried to google that error but it's such a common keyword that I am unable to find anything that is related to my issue. I am probably missing something obvious, I am new to Python and Django.
Note: In the documentation screenshot there is one form field missing which is there in my local environment. It's the algorithm field.

After debugging for so many hours I came to this, please include it in your settings.py file and it works. Maybe it is a bug since we defined our app as confidential with authorization_code grant type but oauth_provider is thinking it as public and trying to validate for pkce.
OAUTH2_PROVIDER = {
"PKCE_REQUIRED": False
}

Related

difficulty getting oauth 2 token file with yagmail

I am trying to use the python package yagmail to send emails but am having a tough time getting authorization to work.
My issue is getting an Oauth 2 token, but there is a disconnect with yagmail, as specified in a github thread. As stated in this post, https://github.com/kootenpv/yagmail/issues/143, it appears that google does not supply the credential file in the correct format. But I tried a bunch of things and each has its own problem.
When I set up a Client ID in the Google API console, download the
json as credentials.json and let the system create the token.json,
things work to a point: I am brought through google to "pick an
account, do you want to continue" and token is created. I am able to
print labels for the gmail account. But when I issue
yag.send(to='xxx#gmail.com', subject='Testing Yagmail',
contents='Hurray, it worked!'), I get an error "TypeError:
refresh_authorization() got an unexpected keyword argument 'token'."
When I look at the token file, it does contain the key 'token' which
it should not per this github post https://github.com/kootenpv/yagmail/issues/143#issuecomment-527115298][2].
If I go into the token and edit it to reflect the the expected
contents as identified in the above link by removing keys that are
not specified and prefixing the names with 'google_', I get an error
"ValueError: Authorized user info was not in the expected format,
missing fields refresh_token, client_id, client_secret." It doesn't
seem to like the 'google_' prefix.
editing the token file as above without the 'google_' prefix seems to
get further producing a different error "An error occurred:
<HttpError 403 when requesting
https://gmail.googleapis.com/gmail/v1/users/me/labels?alt=json
returned "Request had insufficient authentication scopes"
I am stuck. Relatively new to Oauth2, but it seems others are able to use yagmail. Is there a trick I am missing? I originally posted on Github because I found that other related post, but it seems SO is more geared toward Q&A. Is there a relation betweeen Github and SO? Difference?
Thanks for any assistance,
Brian
I finally found a solution and the answer was hidden in plain sight.
First the Oauth authorization needed to be set up as outlined in this post (which is excellent): Sending email via Gmail & Python
As stated, when yagmail is run the first time the authorization process gives instructions, the final stating to "Navigate to the following URL to auth:" and asks "Enter the localhost URL you were redirected to:"
The problem is the browser window shows what appears to be an error message, a sad face with a message "This site can’t be reached, localhost refused to connect, reload", etc. I never thought this was expected behavior. The url is the one being navigated to in the error screen.
Simply stating the error should be expected, and the url needs to be copied and pasted in the post above would help a lot.

AADSTS90102 error when using django-microsoft-auth for SSO with Azure AD

I followed the steps in this tutorial to enable SSO with Azure Active Directory for the admin portion (to start) of my Django app:
https://django-microsoft-auth.readthedocs.io/en/latest/usage.html
Navigating to /admin yields this page, which is good:
Clicking Microsoft brings up this new window:
The important error seems to be:
AADSTS90102: 'redirect_uri' value must be a valid absolute URI.
In this window, I used the browser console and found that a GET request was being made like this:
https://login.microsoftonline.com/50ce...90ac7/oauth2/v2.0/authorize?response_type=code&client_id=f4...27&redirect_uri=https,https://example.org/microsoft/auth-callback/&s...
Note the redirect_uri=https,https://.... It seems like that leading "https," is superfluous and is causing the problem. Any ideas where that could be coming from?
In my Azure app, the redirect URI is set to https://example.org/microsoft/auth-callback/:
I'm using Python 3.9.6, Django 3.2, django-microsoft-auth 2.4.0, NGINX 1.18.0, uvicorn 0.14.0
I've searched for help on this and haven't found anything relevant to my situation. Thanks in advance!
Based on the SO Thread Reference.
Use http as the redirect URI instead of https to resolve the issue in most cases.
use
http://localhost:8080/microsoft/auth-callback/
Instead of
https://localhost:8080/microsoft/auth-callback/
If there is a option,
Use localhost:8080 into the table django_site
Reference SO Thread: django-microsoft-auth : The provided value for the input parameter 'redirect_uri' is not valid
As you think, the first https is superfluous, you just need to delete it.
https://login.microsoftonline.com/50ce...90ac7/oauth2/v2.0/authorize?response_type=code&client_id=f4...27&redirect_uri=https://example.org/microsoft/auth-callback/&s...
By the way, I think there is no problem with the redirect_uri you set in the Azure portal.
I guess it is a problem of the redirecting URL. The example URL is coming from django site table. So first of all you need to enable the site:
#in settings.py
SITE_ID = 1
Afterwards you can go to the admin interface and set the url of the site to the correct domain. From my experience I know that it won't work without that.

Gaining authorization to modify Spotify playlists using spotipy for Python3

I'm currently attempting to use spotipy, a python3 module, to access and edit my personal Spotify premium account. I've followed the tutorial on https://github.com/plamere/spotipy/blob/master/docs/index.rst using the util.prompt_for_user_token method by entering the necessary parameters directly (username, client ID, secret ID, scope and redirect uri). Everything seems to be fine up to this part. My code (fillers for username, client id and client secret for security reasons) :
code
It opens up my default web browser and redirects me to my redirect url with the code in it. At this point, I copy and paste the redirect url (as prompted) and hit enter. It returns the following error:
Error
My redirect uri is 'http://google.com/' for this specific example. However, I've tried multiple redirect uris but they all seem to produce the same error for me. (and yes, I did set my redirect uri as whitespace for my application). I've spent hours trying to fix this issue by looking at online tutorials, trying different redirect urls, changing my code but have yet to make any progress. I'm hoping I am just overlooking a simple mistake here! Any feedback on how to fix this is much appreciated!
If it matters: I'm using the IDE PyCharm.
I had to use two different solutions to deal with the redirect_uri issue depending on which IDE I was using. For Jupyter Lab/Notebook, I could use a localhost for the redirect_url
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="your_client_id", client_secret="your_client_secret", redirect_uri="https://localhost:8890/callback/", scope="user-library-read"))
For Google Colab, I had to use a publicly accessible website. I think "https://google.com/" should work but I used my band's website so I'd remember that the redirect_uri had to match the one in your Spotify Develop dashboard settings.
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="your_client_id", client_secret="your_client_secret", redirect_uri="https://yourwebsite.com/", scope="user-library-read"))
I just ended up using my bands website because it was easier for me to remember. Make sure to go to the Spotify developer dashboard (https://developer.spotify.com/dashboard/applications) and match the redirect_uri with what you are planning to use at that time.
I think it is your redirect URL - working for me with:
import os
import spotipy.util as util
# credentials
user = 'username'
desired_scope = 'playlist-modify-private'
id = os.environ.get('SPOT_CLIENT')
secret = os.environ.get('SPOT_SECRET')
uri = 'https://localhost'
token = util.prompt_for_user_token(username=user,
scope=desired_scope,
client_id=id,
client_secret=secret,
redirect_uri=uri)
I think for your redirect url spotify requires the initial http(s) part - don't forget to add it to the white-list in your Spotify for Developers app too, as otherwise you will get 'invalid-redirect-uri'.

Spotipy (Spotify's Web API Python wrapper) examples failing

I cloned and installed Paul Lamere's Python wrapper for the Spotify Web API via python setup.py install but I can't seem to run some of the examples correctly.
Specifically, when I try to run user_playlists_contents.py or user_starred_playlist.py, a browser is launched and I'm directed to the Spotify login page. After logging in, I get a Spotify error within the browser that only says: "Oops! Something went wrong." The script asks for the URL I was redirected to, but entering in both the URL of the login page and the URL of the error page (obviously) trigger an error within the Terminal: spotipy.oauth2.SpotifyOauthError: Bad Request
At first I was using a Facebook-connected Spotify account and logging in to Spotify through Facebook when prompted, so I thought that might be an issue. However even after creating a new email-only Spotify account and running the scripts on this new email-only username I got the same results.
I also tried registering a new App in my Spotify developer account and using its CLIENT_ID, CLIENT_SECRET, and REDIRECT_URI in the examples/util.py but this didn't seem to do anything. It seems unlikely anyways that modifying examples/util.py is necessary.
Thinking this might be a browser issue I also reset my browser (Chrome) and after that didn't work I tried switching Safari to the default browser but that also did nothing.
Both these scripts depend on prompt_for_user_token() which is defined in examples/util.py, and seems to be where things are going wrong.
What am I doing wrong? Have I missed something painfully obvious? Thanks in advance.
prompt_for_user_token method looks as below:
def prompt_for_user_token(username, scope=None):
''' prompts the user to login if necessary and returns
the user token suitable for use with the spotipy.Spotify
constructor
'''
client_id = os.getenv('CLIENT_ID', 'YOUR_CLIENT_ID')
client_secret = os.getenv('CLIENT_SECRET', 'YOUR_CLIENT_SECRET')
redirect_uri = os.getenv('REDIRECT_URI', 'YOUR_REDIRECT_URI')
.
.
which requires you to set CLIENT_ID, CLIENT_SECRET and REDIRECT_URI environment variables before executing the example. You get these values by creating an app at My Applications section of Spotify Developer Site
In Unix, you can set environment variables in the command line as follows:
export CLIENT_ID={yourclient}
export CLIENT_SECRET={yoursecret}
export REDIRECT_URI={your redirect uri}
Then you need to copy and paste the full url you were redirected to on browser to proceed.
I have a similar problem and found at least a work around solution. See here. I got this to work by passing the client_id, client_secret, redirect_uri as agruments in util.prompt_for_user_token. I had to copy and paste the entire URL including code. I did not mess with util.py at all.

GData and OAuth in Python: Unable to convert request token to access token

I am trying to implement a button on a web-based dashboard that allows a user to export the current data to a Google Spreadsheet using OAuth and GData API. Currently, I can get the user to a login/grant access page, but if I add the line to convert the request token to an access token, I receive:
"RequestError: Unable to upgrade OAuth request token to access token: 400, parameter_absent
oauth_parameters_absent:oauth_token"
I am following the instructions for OAuth 2 on this page:
https://developers.google.com/gdata/docs/auth/oauth
and have read both PyDocs for the Google APIs and found no details on this issue:
http://gdata-python-client.googlecode.com/hg/pydocs/gdata.docs.client.html#DocsClient
(Won't let me post a this hyperlink but other Pydoc is same URL but replace the piece after pydocs/ with gdata.gauth.html#ClientLoginToken)
This is the code that works:
def createDocsClient(self, oauth_callback_url):
docsClient = gdata.docs.client.DocsClient(source='RiskOps-QualityDashboard')
request_token = docsClient.GetOAuthToken(SCOPES, oauth_callback_url, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)
domain = None
auth_url = request_token.generate_authorization_url(google_apps_domain=domain)
self.redirect(str(auth_url))
request_token = gdata.gauth.AuthorizeRequestToken(request_token, self.request.uri
With the above code, I get to a grant access page and if you click the grant access page, you get a 404 error because it doesn't know where to go after (as expected), but the page has the proper URL displayed listing an oauth_verifier and oauth_token. The "AuthorizeRequestToken" line is supposed to use that URL to authorize the token so up to this line, everything seems to work.
When I add the following line right after the code above, I get the "RequestError" I wrote about:
access_token = docsClient.GetAccessToken(request_token)
I've tried different combinations of nesting the calls within each other, using the AeSave and AeLoad (as the instructions mention might be needed but I'm not sure if my case calls for it) and many other random and unsuccessful ideas and nothing is really giving me a good idea of what I'm missing or doing wrong.
Would really appreciate and help or any ideas anyone has.(If you can't tell, I'm fairly inexperienced when it comes to real-world code (as opposed to academic code). Thanks so much.

Categories

Resources