OAuth 2.0应用场景
程序员对Gitee
和Github
都不陌生,Github
可能是起源时间最早、用户范围最大的代码开源仓库,Gitee
作为国产代码仓库的后起之秀,在用户模块也是做到了兼容Github
的功能,如,在Gitee
的登录界面可以通过Github
授权的方式登录。这就是今天我要讲的OAuth 2.0
,大家可以去Gitee
体验一下UI交互流程,以更形象的理解OAuth 2.0
的授权流程。
OAuth2.0业务角色
作用:
使客户端安全可控的获取”用户“授权,与服务提供商交互。
OAuth 2.0运行流程
摘自RFC 6749.
用户授权方式有五种:
- 授权码模式(authorization code)
- 简化模式(implicit)
- 密码模式(resource owner password credentials)
- 客户端模式(client credentials)
授权方式-以authorization-code为例
认证流程:
- 用户访问客户端,客户端跳转至认证服务器认证页面
- 用户选择是否授权
- 若选择授权,则用户自行选择认证登录,如:验证码、账号密码等
- 认证服务器发放Authorization Code,页面从认证服务器Redirection URI到Client
- Client拿Authorization Code去请求认证服务器
- 若认证无误,则发放Access Token/Refresh Token
信息补充
Access Token: An OAuth Access Token is a string that the OAuth client uses to make requests to the resource server.
Refresh Token: An OAuth Refresh Token is a string that the OAuth client can use to get a new access token without the user’s interaction.
Scope: Scope is a mechanism in OAuth 2.0 to limit an application’s access to a user’s account. An application can request one or more scopes, this information is then presented to the user in the consent screen, and the access token issued to the application will be limited to the scopes granted.
更为形象的流程-来自阿里云
SP:客户端
IDP:认证服务器
A步骤中,客户端申请认证的URI,包含以下参数:
- response_type:表示授权类型,必选项,此处的值固定为"code"
- client_id:表示客户端的ID,必选项
- redirect_uri:表示重定向URI,可选项。认证服务器认证完成后,重定向到客户端的uri
- scope:表示申请的权限范围,可选项
- state:表示客户端的当前状态,可以指定任意值,认证服务器会原封不动地返回这个值。
如:
http://example.com?code=xxx&state=test&response_type=code&client_id=xxxx&redirect_uri=xxxx.com
C步骤中,服务器回应客户端的URI,包含以下参数:
- code:表示授权码,必选项。该码的有效期应该很短,通常设为10分钟,客户端只能使用该码一次,否则会被授权服务器拒绝。该码与客户端ID和重定向URI,是一一对应关系。
- state:如果客户端的请求中包含这个参数,认证服务器的回应也必须一模一样包含这个参数。
D步骤中,客户端申请服务端令牌,入参有:
返回值有:
认证流程完成,接下来就可以拿服务端生成的Access Token获取服务端的资源了。
更新token
Access Token 一般都设有过期时间,在访问时如果客户端的访问令牌已经过期,则需要使用”更新令牌“申请一个新的访问令牌。入参使用grantType、refreshToken、scope。