Google Identity Services SDK - 弹出模式下的授权代码模型 - 如何请求刷新/访问令牌?

1 oauth-2.0 google-oauth

我正在尝试使用 Google Identity Services SDK 实现授权代码模型,如使用代码模型中所述。我想使用弹出模式。

我设法初始化代码客户端并使用以下 Javascript 代码接收身份验证代码:

tokenClient = google.accounts.oauth2.initCodeClient({
  client_id: CLIENT_ID,
  scope: SCOPES,
  callback: '', // defined later
  ux_mode: 'popup',
})

...

tokenClient.requestCode({prompt: 'consent'});
Run Code Online (Sandbox Code Playgroud)

当我在回调中收到身份验证代码时,我将其中继到平台上的端点,如步骤 5:交换刷新和访问令牌的授权代码中所述,并且我尝试在 Python 中将身份验证代码交换为刷新和访问令牌:

flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    'client_secret.json',
    scopes=scopes,
    state=state
    redirect_uri=redirect_uri
)

flow.fetch_token(code=code)
Run Code Online (Sandbox Code Playgroud)

问题是我将此代码与空的redirect_uri一起使用,我收到错误“缺少redirect_uri参数”。如果我指定在 Google Cloud Console 中定义的重定向网址,则会收到错误“redirect_uri 不匹配”。如果我尝试使用与初始弹出请求中发送的相同的redirect_uri(Google 似乎storagerelay://...在本例中使用),我会收到一条错误消息“它不符合 Google Oauth2 政策”。

Mat*_*ers 5

看来,在任何授权流程中,当您在客户端获取授权代码并将其传递到服务器进行令牌交换时,您必须使用字符串文字"postmessage"作为redirect_uri.

flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    'client_secret.json',
    scopes=scopes,
    state=state
    redirect_uri="postmessage"
)

flow.fetch_token(code=code)
Run Code Online (Sandbox Code Playgroud)

奇怪的是,大多数谷歌客户端库的文档中似乎都没有这个非常重要的事实,但它对我有用。希望这可以帮助!