一、介绍
OAuth2是一个授权框架,使应用程序能够访问其它公司提供的资源,比如腾讯、阿里、华为等公司的开放平台。OAuth2为Web、桌面程序、移动程序提供了一整套的授权流程。
二、OAuth角色
OAuth一共定义了4个角色:
- resource owner
可以授权其它应用访问受保护的资源的实体。如果资源拥有者表示一个人,它就是最终用户。 - resource server
拥有受保护资源的服务器,能够使用token
接受和响应受保护资源的请求。 - client
通过资源拥有者授权访问受保护资源的程序 - authorization server
用来验证并且授予访问权限的服务,授权成功后将访问token
颁发给client
。
三、协议流程

1、client
请求resource owner
授予权限。
2、resource owner
同意授权,并且将授权许可证颁发给client
。
3、client
通过身份验证和授权许可证来向authorization server
请求access token
。
4、authorization server
在验证client
身份和授权许可证有效后,向client
颁发access token
。
5、client
通过access token
访问resource server
上受保护的资源。
6、resource server
在验证access token
的有效性后,返回受保护的资源。
以上流程是一个基本的授权访问流程,不过根据授权方式不同流程会有差异。下面将介绍OAuth2的4种授权方式。
四、OAuth2授权模式
OAuth2一共定义了4种授权模式,另外还定义了一个机制用来定义额外的授权模式。这里主要介绍4种基本的授权模式:
- Authorization Code
适用于拥有后台服务的应用 - Implicit
适用于移动app或web app等没有后台服务的应用 - Resource Owner Password Credentials
可信任的应用,同一家公司开发的应用 - Client Credentials
后台服务之间api访问
Authorization Code

(A) client
通过用户代理将用户引导至授权页面
(B)authorization server
验证resource owner
身份,并且确定resource owner
是授予还是拒绝client
的access
请求
(C)如果resource owner
允许client
访问,authorization server
将用户代理重定向到client
请求时提供的redirection URI
,同时附上authorization code
(D)client
使用authorization code
,向authorization server
的token endpoint
请求access token
。请求时可以附带(C)中的redirection URI
(用于验证你提交的URI跟client
注册的URI是否一致)
(E)authorization server
验证client
身份和authorization code
以及redirection URI
。如果验证有效,authorization server
返回access token
和refresh token
(可选项)
Implicit

(A) client
通过用户代理将用户引导至授权页面
(B)authorization server
验证resource owner
身份,并且确定resource owner
是授予还是拒绝client
的access
请求
(C)如果resource owner
允许client
访问,authorization server
将引导用户代理重定向到client
请求时提供的redirection URI
,同时附上URI fragment
。URI fragment
包括了access token
(D)用户代理通过向虚拟主机(www、FTP、Email等空间服务)请求client
资源(客户端自己的资源)来进行重定向
(E)虚拟主机的client
资源返回一个web页面,该页面可以访问完整的redirection URI
以及包含了access token
的URI fragment
。
(F)用户代理运行web页面中的script
脚本,用来提取URI fragment
中的access token
(G)用户代理将access token
发送给client
Resource Owner Password Credentials

(A)resource owner
向client
提供账号和密码
(B)client
通过resource owner
的账号和密码来向authorization server
请求获取access token
(C)authorization server
在验证了client
身份以及resource owner
的账号和密码有效后,向client
颁发access token
Client Credentials Grant

(A)client
通过authorization server
进行身份验证,并请求access token
(B)authorization server
在验证了client
身份有效后,向client
颁发access token
网友评论