Google API 授权操作

2018-01-22  本文已影响0人  前端进城打工仔

前言

Google 提供了很多API:如Directory API | Google Developers 可以对用户、组进行操作,如把人加到Google group中、获取一个组里的用户、获取组的setting等等

image.png

在使用Directory API的时候Google有它的认证授权机制,其中包含OAuth 2.0,这里也主要介绍OAuth 2.0的授权是怎么进行的。

OAuth授权操作

OAuth是什么,请参考维基百科的说法。

创建一个OAuth client

Google Console页面 进入你的project,如果没有project就创建一个project。然后创建一个credentials。

image.png
这里选择OAuth client ID,如果是web应用就选"Web application",但是在我们的使用场景中是一个后台job,所以选择了"Other"。"Web application"需要你填写Authorized JavaScript origins和Authorized redirect URIs,但是"Other"不需要,只要填写一个名字就够了。

在你创建成功后,会返回一个client ID和client secret。

image.png

获取access token和refresh token

创建client_secret.json文件,下载官网的例子本地运行

{
  "installed": {
    "client_id": "",
    "project_id": "",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "",
    "redirect_uris": [
      "urn:ietf:wg:oauth:2.0:oob"
    ]
  }
}

官网例子,其中SCOPES中是这个token的权限,我们一般根据所需的API的权限赋予不同的值。在启动后,会在控制台打印出一串地址,把地址copy到浏览器中,一步一步认证,然后在浏览器中会返回一个token,把这个token拷贝到控制台中,就会生成一个credentials文件,token最后以json的形式存在TOKEN_PATH目录下的文件中。

当然这个过程中会出现一个error如下:

Project XXXXXXX is not found and cannot be used for API calls. If it is recently created, enable Admin Directory API by visiting [https://console.developers.google.com/apis/api/admin.googleapis.com/overview?project=XXXXXXX](https://console.developers.google.com/apis/api/admin.googleapis.com/overview?project=XXXXXXX) then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.

所以需要到Google Console去enable一下Admin Directory API。之后就会得到这个API的监控数据。如下:

image.png

同时也要注意这些API的限制,例如默认每天最多150000个query,每个用户每100秒内最多1500个query。所以在写代码的时候并发数和总数都需要进行控制。


image.png

之后就可以成功的操作数据了,关于授权需要注意的点:为了安全,一定要根据需求给尽可能小的权限。

参考文档:
Google 各种API的授权操作都是类似的,如下操作:
Authorize Requests
对于使用了Google API的应用,用户访问的时候需要授权获取用户数据,但是可以让domain administrator给应用授予domain-wide权限去获取用户数据,而不需要用户手动去授权。
Perform G Suite Domain-Wide Delegation of Authority
使用Google OAuth 2.0 存取Google API

上一篇下一篇

猜你喜欢

热点阅读