git地址奉上git
https://gitee.com/luck/oauth2.git
#SpringBoot2 + spring-security-oauth2 使用示例,实现了如下四和受权模式。spring
(1)受权码模式(Authorization Code)sql
(2)受权码简化模式(Implicit)json
(3)Pwd模式(Resource Owner Password Credentials)服务器
(4)Client模式(Client Credentials)app
项目提供的全部用户和client 的密码都为123456spring-boot
#安装运行ui
导入oauth2.sqlthis
修改 application.yml的数据源3d
运行
mvn spring-boot:run
http://localhost:8080/user/info
提示须要认证:
<oauth> <error_description> Full authentication is required to access this resource </error_description> <error> unauthorized </error> </oauth>
http://localhost:8080/oauth/authorize?client_id=client_3&response_type=code&scope=read&redirect_uri=http://localhost:8080/code?client_id=client_3
由于这里会弹出 HTTP Basic认证,必须登陆的用户才能申请 code。
username=user_1
passpord=123456
如上用户名密码是交给 SpringSecurity 的主过滤器用来认证的
oauth/authorize 认证成功,会根据 redirect_uri 执行 302 重定向,而且带上生成的 code,注意重定向到的是 8080 端口,这个时候已是另一个应用了。
http://localhost:8080/code?client_id=client_3&code=c3FbHM
代码中封装了一个 http 请求, 使用 restTemplate 向 认证服务器发送 token 的申请,固然是使用 code 来申请的,并最终成功获取到 access_token
{ "access_token":"5db93d64-2252-4349-90a3-e4d6637f90ae", "refresh_token":"5a67faae-38ed-4e5c-a809-c9d07c16abcb", "scope":"read", "token_type":"bearer", "expires_in":42494 }
http://localhost:8080/user/info?access_token=5db93d64-2252-4349-90a3-e4d6637f90ae
正常返回信息
{ "password":null, "username":"user_1", "authorities":[{"authority":"ROLE_USER"}], "accountNonExpired":true, "accountNonLocked":true, "credentialsNonExpired":true, "enabled":true }
Implicit与Authorization_code 区别是 Implicit不须要验证client_secret,请求若是成功会直接返回 token
获取受权码
http://localhost:8080/oauth/authorize?response_type=token&client_id=client_4&scope=read&redirect_uri=http://localhost:8080/param
若是成功会重定向到URL(token在URL里)
http://localhost:8080/param#access_token=85090391-2c33-4a75-a989-116bb06b0c5a&token_type=bearer&expires_in=42962&scope=read
请求 Access Token:
http://localhost:8080/oauth/token?username=user_1&password=123456&grant_type=client_credentials&scope=read&client_id=client_1&client_secret=123456
正常返回信息
{ "access_token":"fb1a1d03-9658-4d92-822a-d988c9f7a923", "token_type":"bearer", "expires_in":43148, "scope":"read" }
请求 Access Token:
http://localhost:8080/oauth/token?grant_type=client_credentials&scope=read&client_id=client_1&client_secret=123456
正常返回信息
{ "access_token": "fb1a1d03-9658-4d92-822a-d988c9f7a923", "token_type": "bearer", "expires_in": 42811, "scope": "read" }