pythonoauth-2.0google-cloud-functionsgoogle-auth-library

Python - Google OAuth generate token from authorization code


I have an python google cloud function which receives a OAuth authorization code as an argument. I want to exchange this code for a token which can be used to authenticate a service object.

The code is generated externally and passed to this function as a string arguement.

I've looked at the documentation for google_auth_oauthlib.flow. But it expects a flow object created to handle the auth. In my case I only have the code as the result.

How can I exchange a authorization code as string into a token?


Solution

  • You need a few more pieces of information than just the Authorization Code. Google's docs for how to exchange an Authorization Code into an Access Token are here: Exchange authorization code for refresh and access tokens.

    Specifically, in addition to the code, you need:

    Most of these (client_id, client_secret, grant_type) are static, so you can use them as configuration in your cloud function. The redirect_uri could be static if you're sure of the flow that generated the code.

    With that information, you should be able to create the Flow object in your linked example and fetch the token.

    As an alternative to storing all this configuration in your cloud function, you could use a managed OAuth service like Xkit (where I work), which handles the authorization process and lets you retrieve access tokens from anywhere (including cloud functions) with just an API key.