I am currently trying to integrate a Google Sign-In feature into my local Flask Web Application with OAuthlib. While trying to run the finished implementation of the Flask Google-Login feature as shown here at RealPython, I ran into this error:
oauthlib.oauth2.rfc6749.errors.InvalidClientError: (invalid_client) Unauthorized
which points to this line of code in my routes.py
file:
client.parse_request_body_response(json.dumps(token_response.json()))
I have no clue as to why I'm getting this error, how do I resolve this?
Here are samples from both my app/__init__.py
file and routes.py
file:
app/__init__.py
import os
from flask import Flask
from config import Development
from flask_caching import Cache
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from oauthlib.oauth2 import WebApplicationClient
app = Flask(__name__)
app.config.from_object(Development)
cache = Cache(app)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID")
client = WebApplicationClient(GOOGLE_CLIENT_ID)
from app import routes, forms, login, models
app/routes.py
import os
...
GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID")
GOOGLE_CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET")
GOOGLE_DISCOVERY_URL = (
"https://accounts.google.com/.well-known/openid-configuration"
)
def get_google_provider_cfg():
return requests.get(GOOGLE_DISCOVERY_URL).json()
...
@app.route("/login-google")
def login_google():
google_provider_cfg = get_google_provider_cfg()
authorization_endpoint = google_provider_cfg["authorization_endpoint"]
request_uri = client.prepare_request_uri(
authorization_endpoint,
redirect_uri=flask.request.base_url + '/callback',
scope=["openid", "email", "profile"],
)
return flask.redirect(request_uri)
@app.route("/login-google/callback")
def callback():
code = flask.request.args.get("code")
google_provider_cfg = get_google_provider_cfg()
token_endpoint = google_provider_cfg["token_endpoint"]
token_url, headers, body = client.prepare_token_request(
token_endpoint, authorization_response=flask.request.url,
redirect_url=flask.request.base_url, code=code
)
token_response = requests.post(
token_url, headers=headers,
data=body, auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
)
client.parse_request_body_response(json.dumps(token_response.json())) ## <--- Error Occurs Here!
userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
uri, headers, body = client.add_token(userinfo_endpoint)
userinfo_response = requests.get(uri, headers=headers, data=body)
flags = userinfo_response.json().get("email_verified")
...
You mean you want to make google - login to your flask website? I have my own code, it work well First, init.py
Second, in main.py, you can change to app.py, for easy code in future, i think you should user Blueprint
Third, in html
For my code, you have to make the model in models.py
To use model, i use the Flask-Login