仓前OAuth 2.0研究组

通过Google OAuth Playground理解Googl

2017-05-07  本文已影响92人  阿呆少爷

Google OAuth Playground是个好东西啊。我觉得任何面向普通用户的产品都应该提供Playground,用简单的交互方式鼓励用户去学习和探索。

下面使用Google OAuth Playground来体验一下gmail。首先申请gmail的接口权限。scope里面我加了profile

Paste_Image.png Paste_Image.png Paste_Image.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。右边可以看到请求和响应的过程及数据。

Paste_Image.png

第三步是从List possible operations里面选取自己要访问的服务。

Paste_Image.png

这个https://www.googleapis.com/gmail/v1/users/{userId}/labels接口可以获取到用户的自定义标签。唯一需要填写的是userId。那么userId是什么呢?这个时候又得用上 https://jwt.io 解开 id_token,其中的sub就是userId啦。sub的定义可以参看:JSON Web Token (JWT)

Paste_Image.png image.png

可以看到成功获取到用户的自定义标签数据,非常棒。

Paste_Image.png

OAuth 2.0标准将客户端分为web applicationuser-agent-based applicationnative 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=tokenimplicit 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.

image.png

Web应用不好保存RefreshToken,OAuth Playground在获取auth code的请求里面加上了access_type=offline,这样在换取的token的时候服务器端才会返回RefreshToken。如果去掉这个参数,是不会有RefreshToken的。

image.png
上一篇 下一篇

猜你喜欢

热点阅读