Search code examples
pythonflaskgoogle-oauthgoogle-authenticationgoogle-api-python-client

Python - Google OAuth2 - Wrong number of segments in token


I'm trying to connect my Android Flutter project to my Flask API server and the client app works as intended. The problem is that even hardcoding the OAuth2 access token into the server gives the following error message. I'm confused why it even occures. Official Google documentation on Python backend OAuth2 handling is here.

Error message: Wrong number of segments in token: b'ya29.GluNBQsv_8FW2-jjI0w.....

Code:

import flask
from flask import jsonify, request, redirect, url_for
from google.oauth2 import id_token
from google.auth.transport import requests

#### SKIPPED INIT AND OTHER CODE ####

@app.route('/', methods=['POST'])
def index():
    token = "ya29.GluNBQsv_8FW2....." # 129 chars in total

    try:
        idinfo = id_token.verify_oauth2_token(token, requests.Request(), None)
        print(idinfo['email'])
    except Exception as ex:
        print(ex)
        data = {
            'status': 403,
            'message': 'Authorization required',
        }
        response = jsonify(data)
        response.status_code = 403
        return response

Solution

  • what you are passing is the access_token and not the id_token. when you initiate a Google login it send u a "code" then u pass it to token end point and it give u three things. access_token, id_token and refresh_token(based on condition). what that function want is id_token.