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?
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:client_id
: The client ID obtained from the API Console [Credentials page] |(https://console.developers.google.com/apis/credentials).client_secret
: The client secret obtained from the API Console Credentials page.grant_type
:authorization_code
redirect_uri
: The redirect URI used in the initial authorization request. If this is for a CLI (or similar) that might beurn:ietf:wg:oauth:2.0:oob
(for out-of-band)Most of these (
client_id
,client_secret
,grant_type
) are static, so you can use them as configuration in your cloud function. Theredirect_uri
could be static if you're sure of the flow that generated thecode
.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.