oAuth2 浅析

512 阅读1分钟

oauth2

oauth2 介绍

OATUH 2.0 RFC

OATUH 2.0 科普

oauth2 的四种授权模式

授权码授权模式(Authorization Code Grant)

参见 RFC Code Grant

流程图

code grant flow

如图示

  • client 为用户
  • user-agent 一般指浏览器
  • resource owner: 资源拥有者
  • Authorization Server: 认证服务器

步骤解释

A)

客户端通过代理(web browser) 向资源服务器请求资源,user agent 代理到授权服务器。这一步,请求链接一般长这个样子:

https://xxx.com/oauth/authorize?
  response_type=code&
  client_id=xxx&
  redirect_uri=client_call_uri&
  scope=base&
  state=xxx
  • response_type:  指定授权类型,这里固定为 code (下面会有 password,token, client_credentials)
  • client_id: 客户 id, 表明请求人身份
  • redirect_uri: 授权后重定向的地址
  • scope: 授权范围
  • state: 重定向后,会原样返回, 可以用来防止 csrf 攻击
B)

授权服务器要对资源所有者进行身份认证并确认资源所有者是授予还是拒绝该请求。

C)

授权服务器跳转 redirect_uri , 同时附带一个授权码(code): https://redirect_uri?code=xxx&state=xxx

D)

用户根据这个 code , 请求 token, 这步的链接一般长这个样子:

https://xxx/oauth/token?
 grant_type=authorization_code&
 code=xxx&
 redirect_uri=xxx&
 client_id=xxx&
 client_secret=xxx
  • grant_type: 授权类型, 这里固定为 authorization_code

  • code: 就是你刚刚拿到的 code

  • redirect_uri: 这一步要保证这里的 uri 和之前的 uri 一致

  • client_id & client_secret :  身份验证

E)

返回 access token, (或者带上 refresh token)

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
    "access_token":"2YotnFZFEjr1zCsicMWpAA",
    "token_type":"example",
    "expires_in":3600,
    "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
    "example_parameter":"example_value"
}

隐藏授权模式(Implicit Grant)

tools.ietf.org/html/rfc674…

密码授权模式(Resource Owner Password Credentials Grant)

tools.ietf.org/html/rfc674…

客户端凭证授权模式(Client Credentials Grant)

tools.ietf.org/html/rfc674…

微信示例

微信 OAUTH 2.0 对接文档

wechat oauth2 flow