question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Problem with OAuth2

See original GitHub issue

OAuth2 fails to authenticate using justpy redirect.

  • I have two versions of a simple Google OAuth2 authenticator. The Flask one works but the JustPy one fails.
  • This line (with a valid client ID) is not redirecting correctly:
jp.redirect("https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=SOME_CLIENT_ID.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Foauth-authorized%2Fgoogle&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&state=SOME_STATE&access_type=offline&include_granted_scopes=true")
  • Google responds with:
Error 400: invalid_request
    Missing required parameter: client_id
  • Exactly the same code using a Flask server and flask.redirect is authenticated correctly by Google.
  • (I have os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' in both scripts to allow testing with http rather than https.)
  • Is this a known issue or am I using justpy incorrectly?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:10

github_iconTop GitHub Comments

2reactions
glorietarucommented, Jan 12, 2021

Thanks to your help I finally have this working. FYI:

# server.py

import os
from logbook import FileHandler, debug, error, warn, info
from datetime import datetime
from requests_oauthlib import OAuth2Session
from redislite import StrictRedis
import justpy as jp
import asyncio

os.environ["OAUTHLIB_RELAX_TOKEN_SCOPE"] = "1"  # Prevent "Warning: Scope has changed".
log_handler = FileHandler(f"""{os.environ.get("HOME")}/justpy/logs/server.log""")
rds = StrictRedis(os.environ.get("REDISLITE_DB"), charset="utf-8", decode_responses=True)
print(f"""=====\nConnect to redis via: redis-cli -s {rds.socket_file}\n=====""")
client_id = os.environ.get("GOOGLE_CLIENT_ID")
client_secret = os.environ.get("GOOGLE_SECRET")
redirect_uri = f"""{os.environ.get("JUSTPY_URL")}/oauth-authorized/google"""
authorization_base_url = "https://accounts.google.com/o/oauth2/auth"
token_url = "https://accounts.google.com/o/oauth2/token"
scope = [
     "https://www.googleapis.com/auth/userinfo.email",
     "https://www.googleapis.com/auth/userinfo.profile"
]


def hello_world():
    wp = jp.WebPage()
    jp.Hello(a=wp)
    return wp


def root():
    wp = jp.WebPage()
    jp.Div(a=wp)  # Just so page is not empty
    wp.on('page_ready', login)
    return wp


async def login(self, msg):
    rds.set("server_start", datetime.now().isoformat())
    google = OAuth2Session(client_id=client_id, scope=scope, redirect_uri=redirect_uri)
    authorization_url, state = google.authorization_url(authorization_base_url)
    rds.set("oauth_state", state)
    msg.page.redirect = authorization_url


def oauth_callback(request):
    google = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri, state=rds.get("oauth_state"))
    # Fetch the access token
    #    google.fetch_token(token_url, client_secret=client_secret,
    #             authorization_response=request.url)  # 'URL' object has no attribute 'lower'
    google.fetch_token(token_url, client_secret=client_secret,
             authorization_response=str(request.url))
    r = google.get('https://www.googleapis.com/oauth2/v1/userinfo')
    print(f"""r.content: {r.content}""")
    return jp.redirect("/hello")


jp.Route("/", root)
jp.Route('/oauth-authorized/google', oauth_callback)
jp.Route('/hello', hello_world)


with log_handler.applicationbound():
    jp.justpy()
1reaction
99hatscommented, Jan 5, 2021

Yes, it works.

Read more comments on GitHub >

github_iconTop Results From Across the Web

What is going on with OAuth 2.0? And why you should not use ...
Using OAuth 2.0 for authentication is really, really a bad idea… Problems arising from the use of OAuth 2.0 for authentication does not...
Read more >
Troubleshoot OAuth 2.0 | Microsoft Learn
OAuth 2.0 is a secure but complicated authentication pattern. Many customers report OAuth issues with their custom connectors because their ...
Read more >
How does OAuth 2.0 actually solve the problem?
In order to see how OAuth 2.0 solves this problem of sharing resources, let's look at how this problem was solved before OAuth...
Read more >
Possible Errors - OAuth 2.0 Simplified
If the client ID is not recognized, the authorization server will not redirect the user. Instead, it may display a message describing the ......
Read more >
OAuth 2.0 Errors - Help | Developer Portal for YouTrack and Hub
Token Response Error Codes · Refresh token was issued to another client service. · Refresh token is unknown. · Authorization code is unknown...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found