17

理解 OAuth 2.0 认证流程

 4 years ago
source link: https://lotabout.me/2020/OAuth-2-workflow/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

OAuth 2.0 标准的 RFC 比较难读懂,本文尽量把认证流程说明白。

认证方式

OAuth 2.0 共有 4 种访问模式:

  • 授权码模式(Authorization Code),适用于一般服务器端应用
  • 简化模式(Implicit),适用于纯网页端应用,不过现在推荐使用 PKCE 作为替代
  • 密码模式(Resource owner password credentials),不介绍
  • 客户端模式(Client credentials),不介绍

另外注意 OAuth 服务本身必须是 HTTPS 的,而三方应用可以是 HTTP 的。

Authorization Code

假设我们的网站有一个功能是同步用户在 Github 的所有仓库。对接 OAuth 流程大致分为 5 个步骤:

  1. 在 Github 的 OAuth 页面上注册网站信息。在网站发布前就要做好
  2. 用户点击网站上的“同步 Github 仓库”按钮,开始 OAuth 认证流程
  3. 浏览器弹出 Github 认证窗口,询问“是否允许网站 XXX 的访问”,用户点击“允许”
  4. Github 得知用户点了“允许”后,生成授权码(Authorization Code),并将用户重定向到我们的网站里,网站后台收到授权码后,向 Github 请求ACCESS_TOKEN
  5. 网站后台从 Github 收到 ACCESS_TOKEN,接着向 Github 拉取该用户所有的仓库

具体流程如下图:

nYVNva3.png!web

在授权码方式下,ACCESS_TOKEN 只会存在我们网站的服务器里,用户端从始至终都获取不到这个信息,我们不必害怕用户的电脑中毒了而导致 ACCESS_TOKEN 泄露。

(更多安全相关的考虑参考最后的参考文章)

Implicit

Implicit 是为纯网页应用设计的,与 Authorization Code 模式相比:

CLIENT_SECRET

整体流程如下图:

E36BFfn.png!web

Implicit 设计之初,由于浏览器的同源策略,不允许跨站请求,因此 Authorization Code 不可行。现在由于浏览器普遍支持 CORS ,且 Implicit 本身也在安全风险,目前建议使用 PKCE。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK