OAuth2 Grant type - Authorization Code

概述

授权码(authorization code)方式,指的是第三方应用先申请一个授权码,然后再用该码获取令牌。

这种方式是最常用的流程,安全性也最高,它适用于那些有后端的 Web 应用。授权码通过前端传送,令牌则是储存在后端,而且所有与资源服务器的通信都在后端完成。这样的前后端分离,可以避免令牌泄漏。

整个过程分为如下几步:

1. client发起授权请求,例如

1
2
3
4
5
6
7
8
GET /authorization?
client_id=12345&
redirect_uri=https://client-app.com/callback&
response_type=code&
scope=openid%20profile&
state=ae13d489bd00e3c24

Host: oauth-authorization-server.com

请求包含以下参数

  • client_id :客户端注册后获取的唯一值。
  • redirect_uri :重定向地址。
  • response_type :值为 code 表明授权方式是授权码。
  • scope :访问数据的作用域。
  • state :当前会话的唯一值。

2. 用户登录并确认授权

3. 浏览器重定向到客户端redirect_uri地址,并返回code授权码

1
2
3
4
5
GET /callback?
code=a1b2c3d4e5f6g7h8&
state=ae13d489bd00e3c24

Host: client-app.com

其中的 state 与发起请求的 state 应该一致。

前三步都是在浏览器环境中进行的,后面的步骤则是客户端服务器与 OAuth 服务器之间直接进行通信。

4. 客户端发起请求,使用code交换access token,例如

1
2
3
4
5
6
7
8
POST /token
Host: oauth-authorization-server.com

client_id=12345&
client_secret=SECRET&
redirect_uri=https://client-app.com/callback&
grant_type=authorization_code&
code=a1b2c3d4e5f6g7h8
  • client_id :客户端注册后获取的 client_id。
  • client_secret :客户端注册后获取的 client_secret。
  • redirect_uri :客户端重定向地址。
  • grant_type :声明授权类型为 authorization_code。
  • code :上一步获取的授权码。

5. OAuth 服务器生成access token并响应数据,例如:

1
2
3
4
5
6
7
{
"access_token": "z0y9x8w7v6u5",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "openid profile",
...
}

响应数据可能还包括 refresh token。

6. 客户端调用API请求资源,例如:

1
2
3
GET /userinfo HTTP/1.1
Host: oauth-resource-server.com
Authorization: Bearer z0y9x8w7v6u5

7. 资源服务器响应:

1
2
3
4
5
{
"username": "username",
"email": "123@email.com",
...
}

以上就是一个完整的授权码授权并获取数据的过程。