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" }