google-oauthgoogle-identity

How to set up Google OAuth clients to split authorization and token exchange between client and server?


I'm developing a project in which I'll be gathering consent from Google users to make Google Business Profile API requests on their behalf.

I have a React front-end and a Rails back-end. I've been following this documentation for Google Identity Services, which appears to be Google's latest suggested approach.

Specifically I am trying to follow their most recommended approach of using the Authorization Code model (with the "popup" mode on the client), where I acquire the auth code on my client before handing it off manually to my back-end to exchange for an access token via Google's API SDK and store it.

The problems and confusion begin after I get my auth code and attempt to successfully exchange it. A few questions and issues I'm encountering and struggling to get clarity on from the docs:

  1. Logically I would expect to set up two separate OAuth clients in the Google API console (under one project) - one for my client and one for my API (plus one for mobile clients later, etc.). However attempting the token exchange using a different client ID from the one used on the client is currently failing with a unauthorized_client error. Is this expected behavior, or am I doing something else wrong here?
  2. If I do use the same client ID to perform the token exchange, I get a redirect_uri_mismatch error. This despite having the same single URL specified in the API console, the initial client authorization request and the exchange request parameters. Researching a lot of similar issues online kept leading me to the solution described in this answer involving setting the redirect URI to this bizarre magic "postmessage" string. I don't know what this is or why it works, but this seems ridiculous. It is not mentioned anywhere in any of Google's current official docs. Is this an intended way to do anything or a pure hack?

In summary, is the approach I'm attempting even one that is intended to work? It certainly seems to me like what Google imply I should be doing, and yet the steps in the documentation simply don't appear to work.


Solution

    1. You should use the same client ID on the front-end client and the back-end application when you exchange the access token, etc.

    2. Using GIS redirect with Popup UX flow, you should put postmessage or the origin of the page that received the code for redirect_uri parameter. E.g. if the page you receive the code is https://www.example.com/authorize, you want to put https://www.example.com. It is basically the value you put in "Authorized JavaScript origins" in your Google Cloud Console for your client.

    enter image description here