隨手扎
【用Keycloak學習身份驗證與授權29】JWT權杖格式介紹(1)
總覺得…直接開始說明什麼是JWT格式來著。但感覺這樣會很無聊,不如我們從已經拿到的Token來看吧!
至今爲止,除了存取權杖(access_token
)、更新權杖(refresh_token
)外,還拿到過識別權杖(id_token
)。仔細看三者,都有兩個「.
」可以將權杖分成三個部份。
這些權杖都可以透過JWT.io去解析。總之先透過Password Grant Flow取得access_token
和refresh_token
,或是透過「快速開始」應用取得id_token
。
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ4VXh6WGR4UWpFNDNIZGdYbXJkUjBQZWxXN1ZoZWowbGRkR2NhN0VubXpZIn0.eyJleHAiOjE2MzM5OTIyNzgsImlhdCI6MTYzMzk5MTk3OCwianRpIjoiMzRlOWQxYjEtM2Q3MC00MmYwLTgzOTUtMGU3NDE1OGMxMmRjIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL2F1dGgvcmVhbG1zL3F1aWNrLXN0YXJ0IiwiYXVkIjpbIm15LXF1aWNrLXN0YXJ0LWFwcCIsImFjY291bnQiXSwic3ViIjoiMzQ1YjFiY2EtOTgwNS00YjRiLWEwZjgtZGEyYzcwMTc2YzU5IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoib2F1dGhfdG9vbHMiLCJzZXNzaW9uX3N0YXRlIjoiYjAxM2RmZjMtZmFjMy00YjVmLTkwMjctM2I0NTM1NzVmMzllIiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6WyJodHRwczovL29hdXRoLnRvb2xzIl0sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJkZWZhdWx0LXJvbGVzLXF1aWNrLXN0YXJ0Iiwib2ZmbGluZV9hY2Nlc3MiLCJxdWljay1zdGFydC1leGFtcGxlLXJvbGUxIiwiR3JvdXAgUm9sZSBBIiwidW1hX2F1dGhvcml6YXRpb24iLCJlbXBsb3llZSJdfSwicmVzb3VyY2VfYWN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CGCEz0FQFhkI_CSZaoawIXW_876KlI4iwcuFuuVWcw",
"expires_in": 300,
"refresh_expires_in": 1800,
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI0NjUwNDBkYi1lNGJkLTRiYTYtOWM2Ny02ZWYxZGJmMmUxOWYifQ.eyJleHAiOjE2MzM5OTM3NzgsImlhdCI6MTYzMzk5MTk3OCwianRpIjoiZjZhM2QyMmMtOGM4My00OGFmLTkwMmQtMjg5MjIxYWEzZDFkIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL2F1dGgvcmVhbG1zL3F1aWNrLXN0YXJ0IiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL2F1dGgvcmVhbG1zL3F1aWNrLXN0YXJ0Iiwic3ViIjoiMzQ1YjFiY2EtOTgwNS00YjRiLWEwZjgtZGEyYzcwMTc2YzU5IiwidHlwIjoiUmVmcmVzaCIsImF6cCI6Im9hdXRoX3Rvb2xzIiwic2Vzc2lvbl9zdGF0ZSI6ImIwMTNkZmYzLWZhYzMtNGI1Zi05MDI3LTNiNDUzNTc1ZjM5ZSIsInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsInNpZCI6ImIwMTNkZmYzLWZhYzMtNGI1Zi05MDI3LTNiNDUzNTc1ZjM5ZSJ9.jIbGrKmEG-ltLq2jWXA3l7c3Inq55y_72aaQpamscc0",
"token_type": "Bearer",
"not-before-policy": 1632625952,
"session_state": "b013dff3-fac3-4b5f-9027-3b453575f39e",
"scope": "email profile"
}
因為更新權杖refresh_token
比較短,就以更新權杖為例。「.
」將權杖分成三個部份,由上至下分別為「Header」、「Payload」、「Verify Signature」,也就是描述權杖基礎資料(meta data)的「檔頭」、包含各個cliams權杖資料的「主要內容」、和證明權杖內容未被串改過得「數位簽章」。之後會在一一分析各個部份的內容,現在就先看看如何將前兩個部份主換成叫為容易讀的JSON格式。
關於
kid
、sid
等等意義,與如何處理signature以證明權杖正確性。在iT鐵人賽內容將不會提到。
原本有計劃再一二篇詳細分析JWT格式,以及其他相關的名詞,也就包含:JOSE、JWT、JWS、JWE和JWK。也許會題到JWK,但不會好好說明區別。
前兩個部份是經過Base64編碼的結果,所以同樣可以透過Base64進行解碼:
echo <header|payload>| base64 -di -|python3 -m json.tool
也就是透過以下指令:
echo eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI0NjUwNDBkYi1lNGJkLTRiYTYtOWM2Ny02ZWYxZGJmMmUxOWYifQ| base64 -di -|python3 -m json.tool
可以得到header的結果:
{
"alg": "HS256",
"typ": "JWT",
"kid": "465040db-e4bd-4ba6-9c67-6ef1dbf2e19f"
}
如果拿access_token
的payload
來進行解析,就會得到以下結果:
其中看到不少在User & Group、User & Claim & Profile 所設定和看到的內容。