Oauth2.0 四种认证方式

170 阅读2分钟

OAuth 2.0 的四种主要授权类型(Grant Type)有不同的适用场景和时序流程。以下是每种类型的时序图说明(使用文字描述,模拟时序图结构):

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

image.png 第一步

获取授权码:

http://localhost:8080/oauth/authorize?response_type=code&redirect_uri=http://www.baidu.com&client_id=user_client&scope=all

参数说明
client_id客户端接入标识
response_type授权模式固定code
scope客户端获取权限范围,权限范围配置由oauth_client_details表的autoapprove配置,多个逗号拼接,scope是其中一个或多个,多个逗号拼接
redirect_url跳转url,当授权码申请成功会跳转到此地址上,并在后边带上code参数

第二步

获取token:

http://localhost:8080/oauth/token?grant_type=authorization_code&client_id=base-web&client_secret=123456&code=nnxcQj&redirect_uri=http://www.baidu.com

参数说明
clinet_id客户端接入标识
client_secret客户端密钥
grant_type授权类型,填写authorization_code,授权码模式
code授权码,一次有效
redirect_url跳转url,和获取code时一致

2. 隐式授权模式 (Implicit Grant)

image.png 获取token

http://localhost:8080/oauth/authorize?response_type=token&client_id=admin&redirect_uri=http://www.baidu.com&scope=read&approved=true

参数说明
clinet_id客户端接入标识
response_type隐式授权固定为token
scope客户端权限
redirect_url跳转url,当授权码申请成功后会跳转到此地址,并带token
approved为true时,用户输入账号密码后直接重定向返回token,false需要用户手动授权

3. 密码凭证模式 (Password Credentials)

image.png 获取token:

访问:http://localhost:8080/oauth/token?grant_type=password&username=test123&password=123456

注意:请求头需要

#YWRtaW46MTIzNDU2 字符串为clinet:client_secret 在base64加密后的字符串
authorization:Basic YWRtaW46MTIzNDU2
参数说明
clinet_id客户端接入标识
client_secret客户端密钥
grant_type授权类型,填写authorization_code,授权码模式
username资源拥有者用户名
password用户名密码

4. 客户端凭证模式 (Client Credentials)

image.png

获取token

http://localhost:8080/oauth/token?grant_type=client_credentials&client_id=base-web&client_secret=123456&scope=read

参数说明
clinet_id客户端接入标识
clinet_secret客户端密钥
grant_type授权类型,填写clinet_credentials表示客户端模式
scope授权范围

总结

模式典型场景优点
授权码服务器端 Web 应用、带后端的移动/SPA (PKCE)安全性最高、支持刷新令牌、支持 PKCE流程最复杂、需要后端支持
隐匿纯前端 SPA (历史方案)流程简单、无需后端令牌暴露在 URL、安全性低、不支持刷新令牌
密码高度信任的第一方客户端 (不推荐)用户体验简单、一次请求、支持刷新令牌安全风险极高、客户端接触用户密码、需高度信任
客户端服务器到服务器、机器间通信简单高效、无用户交互不涉及用户、仅代表客户端自身