Search code examples
pythonoauthgoogle-oauthyoutube-data-apigoogle-api-python-client

Google OAuth error 400: redirect_uri_mismatch in Python


first time using OAuth here and I am stuck. I am building a web app that needs to make authorized calls to the YouTube Data API. I am testing the OAuth flow from my local computer.

I am stuck receiving Error 400: redirect_uri_mismatch when I try to run my Google OAuth flow in Python. The error occurs when I access the link generated by flow.run_console()

Here is my code:

os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
client_secrets_file="./client_secret.json"
scopes = ["https://www.googleapis.com/auth/youtube.readonly"]
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets_file, scopes)
flow.redirect_uri = "http://127.0.0.1:8080" # Authorized in my client ID
credentials = flow.run_console() 

This code returns the message:

Please visit this URL to authorize this application: ***google oauth url ***
Enter the authorization code:

Visiting the link results in the following error: URI mismatch error

I tried setting the Authorized Redirect URI in my OAuth Client ID to http://127.0.0.1:8080 since I am testing from my local machine. I also set flow.redirect_uri to http://127.0.0.1:8080 in Python. Using http://127.0.0.1:8080 is currently my only option since the front end has not been set up yet.

I expected the code to authorize my request, since the Authorized URI matches the redirect_uri. But I am still receiving the error.

I have had no issues running the flow from Google's OAuth Playground, if that means anything.

Any help is appreciated, thank you.


Solution

  • Thanks for your help everyone. I was able to find a working solution for my issue from referencing this documentation: https://googleapis.github.io/google-api-python-client/docs/oauth.html

    Here is my solution:

    def get_subscribers(channel_id="Channel_id", 
            client_secrets_file="Client_secret_file", n=50):
        os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
        flow = Flow.from_client_secrets_file(
                client_secrets_file, 
                scopes=["https://www.googleapis.com/auth/youtube.readonly"])
        flow.redirect_uri = "http://localhost"
        auth_url, __ = flow.authorization_url(prompt="consent")
        print('Please go to this URL: {}'.format(auth_url))
        code = input('Enter the authorization code: ')
        flow.fetch_token(code=code)
        youtube = googleapiclient.discovery.build(
            "youtube", "v3", credentials=flow.credentials
        )
        request = youtube.subscriptions().list(
            part="subscriberSnippet",
            forChannelId=channel_id,
            maxResults=n,
            mySubscribers=True
        )
        return request.execute()