keycloak~網站對接(jie)到(dao)Keycloak的步驟
新網站對接到KC的部署
- kc的環境
- 向kc申請自己的客戶端
- kc的登錄接口
- 通過code換token接口
- 刷新token接口
- kc的用戶信息接口
- kc的jwt token說明
1. kc的環境
測試環境:
預發布環境:
生產環境:
2. 向kc申請自己的客戶端
聯系負責(ze)開發kc的同(tong)事,申請一(yi)個(ge)客戶端(duan),需要提供以下信息:
client_id: 客戶端id
client_secret: 客戶端密碼
3. kc的登錄接口
-
/auth/realms/{realm}/protocol/openid-connect/auth?client_id=client_id&response_type=code&redirect_uri=redirect_uri
-
參數說明:
client_id: 客戶端id
response_type: code
redirect_uri: 登錄成功后的回調地址
4. 通過code換token接口
當你把第3步地址復制到(dao)瀏覽(lan)器(qi)后,會重寫向(xiang)到(dao)登錄頁(ye),輸(shu)入正(zheng)確的用(yong)(yong)戶(hu)名和密碼后,提(ti)交后會重定向(xiang)到(dao)來源(yuan)頁(ye),帶在地址上帶著code碼,這個code碼是用(yong)(yong)來換取token的。
- /auth/realms/{realm}/protocol/openid-connect/token
- 請求方式:POST
- 請求參數:
client_id: 客戶端id
client_secret: 客戶端密碼
grant_type: authorization_code
code: 通過登錄成功重寫向后地址上帶著的code
- 返回參數:
{
"access_token": "token",
"expires_in": 1800,
"refresh_expires_in": 1800,
"refresh_token": "refresh_token",
"token_type": "bearer"
}
5. 刷新token接口
通(tong)過第(di)4步獲取到合法的token后,token的有效期(qi)(qi)是(shi)30分(fen)鐘,可以(yi)在kc上配置,如果過期(qi)(qi)了,需要通(tong)過刷新token接(jie)口獲取新的token
- /auth/realms/{realm}/protocol/openid-connect/token
- 請求方式:POST
- 請求參數:
client_id: 客戶端id
client_secret: 客戶端密碼
grant_type: refresh_token
refresh_token: 通過第4步獲取到的refresh_token
- 返回參數:
{
"access_token": "token",
"expires_in": 1800,
"refresh_expires_in": 1800,
"refresh_token": "refresh_token",
"token_type": "bearer"
}
6. kc的用戶信息接口
通過(guo)第(di)4步獲(huo)取(qu)到的(de)token,可以通過(guo)用戶信息接口獲(huo)取(qu)到用戶的(de)信息
- /auth/realms/{realm}/protocol/openid-connect/userinfo
- 請求方式:GET
- 請求頭:
Authorization Bearer token
- 返回參數:
{
"sub": "1",
"email_verified": false,
"name": "admin",
"preferred_username": "admin",
"given_name": "admin",
"family_name": "admin",
"email": "
}
kc的jwt-token字段說明
- exp token過期時間戳
- iat token生成時間戳
- jti token的唯一身份標識,對接token_id或者refresh_token_id,這兩個id在服務端會有存儲,與它頒發的
token里的jti相對應 - iss token的發行機制,kc中的域,例如:
- aud 授權到的客戶端
- sub 當前用戶ID
- typ 認證方式
- azp 當前客戶端client_id
- session_state 當前會話id,瀏覽器中的AUTH_SESSION_ID和AUTH_SESSION_ID_LEGACY
- acr 如果clientSession通過cookie (SSO)進行身份驗證,則使用0,否則為1
- allowed-origins 允許哪種域名使用我們的token
- realm_access 域的權限
- resource_access 客戶端(資源)權限,kc允許你為用戶依照客戶端去授權
- scope 客戶端模板,它將一類jwt中的屬性進行分類,通過這個scope模塊去渲染你的jwt字段