一 参考文章
实战前先看下面5篇文章,以对OAuth2是什么有个初步的了解。
下面4篇是概念篇
http://www.ruanyifeng.com/blog/2019/04/oauth_design.html
http://www.ruanyifeng.com/blog/2019/04/oauth-grant-types.html
http://www.ruanyifeng.com/blog/2019/04/github-oauth.html
http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html
下面这篇是实战篇。
http://www.spring4all.com/article/449
二 基本概念
看完这几篇文章,应该知道oauth2的4种模式:
-
授权码模式(authorization code)
-
简化模式(implicit)
-
密码模式(resource owner password credentials)
-
客户端模式(client credentials)
应该知道以下很重要的一组概念:
(1)Third-party application:第三方应用程序,一般也称为"客户端"(client)。例如:"云冲印"。
(2)HTTP service:HTTP服务提供商,简称"服务提供商",例如:Google服务提供商。
(3)Resource Owner:资源所有者。一般指"用户"(user)。
(4)User Agent:用户代理,一般指浏览器。
(5)Authorization server:认证服务器,即服务提供商专门用来处理认证的服务器。
(6)Resource server:资源服务器,即服务提供商存放用户生成的资源的服务器。它与认证服务器,可以是同一台服务器,也可以是不同的服务器。
三 基本流程
应该知道基本运行流程
(A)用户打开客户端以后,客户端要求用户给予授权。
(B)用户同意给予客户端授权。
(C)客户端使用上一步获得的授权,向认证服务器申请令牌。
(D)认证服务器对客户端进行认证以后,确认无误,同意发放令牌。
(E)客户端使用令牌,向资源服务器申请获取资源。
(F)资源服务器确认令牌无误,同意向客户端开放资源。
四 源码位置
https://github.com/cakin24/oauth2-demo/tree/master/client-credentials
五 测试
1 启动client-credentials
2 password模式测试
浏览器输入
http://localhost:8080/oauth/token?username=user_1&password=123456&grant_type=password&scope=select&client_id=client_2&client_secret=123456
页面显示
{"access_token":"b16810cf-a0b0-4ae2-922e-b8543aaad35e","token_type":"bearer","refresh_token":"4fbd78f2-7240-4303-a1b9-99126f2aa15c","expires_in":43199,"scope":"select"}
浏览器输入
http://localhost:8080/order/1
页面显示
{
"error": "unauthorized",
"error_description": "Full authentication is required to access this resource"
}
浏览器输入
http://localhost:8080/product/1
页面显示
product id : 1
浏览器输入
http://localhost:8080/order/1?access_token=b16810cf-a0b0-4ae2-922e-b8543aaad35e
3 client模式测试
浏览器输入
http://localhost:8080/oauth/token?grant_type=client_credentials&scope=select&client_id=client_1&client_secret=123456
页面显示
{
"access_token": "a68ffc52-909a-42bb-ac7f-252b4d63599c",
"token_type": "bearer",
"expires_in": 43199,
"scope": "select"
}
浏览器输入
http://localhost:8080/product/1?access_token=a68ffc52-909a-42bb-ac7f-252b4d63599c
页面显示
product id : 1
以上测试结果都符合password模式和client模式的预期。