Spring Cloud【Spring Security OAuth2】受權認證

導讀

最近由於工做的緣由作了一個Spring Cloud Oauth2 SSO 的demo 項目 基於Spring Security OAuth2html

正文

安利一下Spring Boot Admin
服務
項目日誌git

受權認證

對外暴露兩個端口

8080 的網關接口 (做爲資源服務器)github

8090 的Oauth2接口 (做爲受權服務器)spring

分紅兩部分

資源服務器json

  • registry 8761 註冊服務
  • api-gateway 8080 網關服務
  • account-service 9000 帳戶服務
  • admin-server 9000 admin服務

受權服務器api

  • oauth2-server 8090 認證服務

啓動順序

資源服務器服務器

  • registry 8761 註冊服務
  • account-service 9000 帳戶服務
  • admin-server 9000 admin服務
  • api-gateway 8080 網關服務

受權服務器app

  • oauth2-server 8090 認證服務

postMan 測試

token 共享基於 JdbcTokenStore 此處能夠換爲 RedisTokenStore 細節能夠參考 Spring Security TokenStore實現3+1詳解post

初始化表結構測試

Drop table  if exists oauth_access_token;
create table oauth_access_token (
  create_time timestamp default now(),
  token_id VARCHAR(255),
  token BLOB,
  authentication_id VARCHAR(255),
  user_name VARCHAR(255),
  client_id VARCHAR(255),
  authentication BLOB,
  refresh_token VARCHAR(255)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Drop table  if exists oauth_refresh_token;
create table oauth_refresh_token (
  create_time timestamp default now(),
  token_id VARCHAR(255),
  token BLOB,
  authentication BLOB
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

step1 登陸受權 獲取 token

爲了方便測試 這次採用密碼模式 4中模式的詳解能夠參考 理解OAuth 2.0

此處的 Authorization 爲應用的client_id的值與secret的值的加密

POST http://localhost:8090/oauth/token HTTP/1.1
 Authorization: Basic U2FtcGxlQ2xpZW50SWQ6c2VjcmV0
 Content-Type: application/x-www-form-urlencoded

 grant_type=password&username=admin&password=admin

響應信息

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
     
{
    "access_token": "63ac3e98-3a82-4837-b399-d4dbb7e1be38",
    "token_type": "bearer",
    "refresh_token": "4e699657-9fd9-4b83-881c-7e9942402353",
    "expires_in": 43011,
    "scope": "user_info"
}

step2 請求資源 攜帶認證信息

GET http://localhost:8080/api/account HTTP/1.1
Authorization: bearer 63ac3e98-3a82-4837-b399-d4dbb7e1be38

響應信息以下

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache

hello account service

step3 註銷

access_token 值爲 上一步獲取到的 access_token 值
Authorization 值爲 應用的client_id與secret的加密

DELETE http://localhost:8090/oauth/token?access_token=63ac3e98-3a82-4837-b399-d4dbb7e1be38 HTTP/1.1
Authorization: Basic U2FtcGxlQ2xpZW50SWQ6c2VjcmV0

響應

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache

註銷成功

項目源碼已託管github

相關文章
相關標籤/搜索