通过Google OAuth Playground理解Googl
Google OAuth Playground是个好东西啊。我觉得任何面向普通用户的产品都应该提供Playground,用简单的交互方式鼓励用户去学习和探索。
下面使用Google OAuth Playground来体验一下gmail。首先申请gmail的接口权限。scope里面我加了profile
。
![](https://img.haomeiwen.com/i1376176/6ebe1865587d2cc6.png)
![](https://img.haomeiwen.com/i1376176/8e83a47cd2751aad.png)
![](https://img.haomeiwen.com/i1376176/334a00d572eee0fe.png)
发出去的请求如下所示。可以看出scope是用户自己填写的scope加上接口对应的scope。
https://accounts.google.com/o/oauth2/v2/auth?
redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground
&prompt=consent
&response_type=code
&client_id=407408718192.apps.googleusercontent.com
&scope=profile+https%3A%2F%2Fmail.google.com%2F
&access_type=offline
接着通过code换取token。右边可以看到请求和响应的过程及数据。
![](https://img.haomeiwen.com/i1376176/c625611c620dda7b.png)
第三步是从List possible operations
里面选取自己要访问的服务。
![](https://img.haomeiwen.com/i1376176/59fad693b474360a.png)
这个https://www.googleapis.com/gmail/v1/users/{userId}/labels
接口可以获取到用户的自定义标签。唯一需要填写的是userId。那么userId是什么呢?这个时候又得用上 https://jwt.io 解开 id_token,其中的sub
就是userId啦。sub
的定义可以参看:JSON Web Token (JWT)。
![](https://img.haomeiwen.com/i1376176/ec74258a9606d949.png)
![](https://img.haomeiwen.com/i1376176/33d9f3f55d6ff5df.png)
可以看到成功获取到用户的自定义标签数据,非常棒。
![](https://img.haomeiwen.com/i1376176/d20a3936bd766fc5.png)
OAuth 2.0标准将客户端分为web application
、user-agent-based application
和native application
三种。web application
的逻辑在服务器端。user-agent-based application
是浏览器直接对接OAuth Endpoint。native application
是native app。
Google OAuth Playground属于web application
,通过浏览器的开发者工具调试可以发现,它并不会直接跟Google OAuth相关的Endpoint打交道,而是使用自己服务器端的接口。
Google OAuth Playground走的是常规的授权码模式,没有使用implicit grant。Google OAuth Server支持implicit grant
,所以下面通过指定response_type=token
走implicit grant
。
//请求中指定response_type=token
https://accounts.google.com/o/oauth2/v2/auth?
redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground
&prompt=consent
&response_type=token
&client_id=407408718192.apps.googleusercontent.com
&scope=https%3A%2F%2Fmail.google.com%2Fmail%2Ffeed%2Fatom
//直接把access token返回回来了,有效期是一个小时,不会有refresh token。
https://developers.google.com/oauthplayground/#
access_token=ya29.GltTBKTMzaEUXE6A-8JwSDkeGsPchWpQ7w8Vwbme_dmIEuJWe_BxUboN7tL7W4d4NC7aYIPteQxal-Rh5ICLQVYxLXF8Yj651Qi-yHkKGpaALcnzdR_QTqiX7N5_
&token_type=Bearer
&expires_in=3600
输入上面的URL,用户完成登录并且在consent页面操作之后,会自动跳到Step 3.
![](https://img.haomeiwen.com/i1376176/0dd410370d02f8b0.png)
Web应用不好保存RefreshToken,OAuth Playground在获取auth code的请求里面加上了access_type=offline
,这样在换取的token的时候服务器端才会返回RefreshToken。如果去掉这个参数,是不会有RefreshToken的。
![](https://img.haomeiwen.com/i1376176/8725314d7024fd30.png)