Google API - Oauth 2.0 Auth token flow

Google API - Oauth 2.0 Auth token flow

本文关键字:Auth token flow API Oauth Google      更新时间:2023-09-26

上下文--

  • 我正在构建一个使用Google Cal和Google+API的web应用程序
  • 我需要获得一个刷新令牌,因为一旦用户使用网站/应用程序进行身份验证,一些调用就会在他们登录后在后台发生(其中许多调用发生在1小时后,其中初始access_token有效)

据我所知,以下是我必须遵循的流程:

  1. 通过Google控制台注册一个Web应用程序API-完成
  2. 通过使用以下配置变量的调用,提示用户使用我的应用程序进行身份验证:

  var config = {
    'client_id': MY_CLIENT_ID',
    'scope': 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email',
    'response_type': 'code',
    'access_type': 'offline'
  };
  1. 然后,使用通过上面的auth()调用返回的Google对象,再次调用以获取access_token和refresh_token

https://developers.google.com/accounts/docs/OAuth2WebServer#refresh

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=CODE_RETURNED
client_id=CLIENT_ID_RETURNED
client_secret=API_CLIENT_SECRET
redirect_uri=API_REDIRECT_API
grant_type=authorization_code

然而,当我尝试运行这个调用时,我总是会遇到一些类型的错误。现在我陷入了以下问题:

{
  error: "redirect_uri_mismatch"
}

我在Google API设置页面和代码中都列出了以下内容作为我的重定向uri:

http://localhost/

以前处理过这种流程的人有什么建议吗?为了获得刷新令牌,我是否需要设置不同的设置?

整个过程之所以失败,是因为我在获取代码的初始调用中没有包含"redirect_uri"。

我应该有:

var config = {
    'client_id': MY_CLIENT_ID',
    'scope': 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email',
    'response_type': 'code',
    'access_type': 'offline',
    'redirect_uri': MY_REDIRECT_URI
 };

然后,这个redirect_uri被数据击中,我设置了一个简单的节点路由来侦听、生成并存储每个经过身份验证的用户的访问和刷新令牌。