什麼是JWT?

What is JWT?

R4 Cheng
1 min readApr 18, 2021
  • JSON Web Token 的縮寫
  • JWT is just for Authorization not for Authentication

先來區分 Authorization 和 Authentication

Authorization: 在登錄期間,確保為同一使用者 (e.g. session ID in cookie)

Authentication: 認證你的帳密是正確的 (登錄當下)

  • JWT 是用來取代 session ID 的位置的

JWT 和 Session ID 最主要的區別是 JWT 不會被儲存在 Server, Server 只負責驗證傳來的 JWT

  • All data stored in the JWT is only base64-encoded (not encrypted)

JWT 組成

// Header
{
"alg": "HS256", // the signing algo
"type": "JWT"
}

// Payload: Where we store information about
{
"id": "XXX"
"username": "XXX"
}

// Verify Signature
{

}

Verify Signature

Only the server has the private key to sign the token

JWT Signing Algorithms

Symmetric digital signature algorithm

  • Use the same private key to sign and verify the token
  • Better for local use, internal services
  • Eg: HS256, HS384, HS512

HS = HMAC + SHA

Asymmetric digital signature algorithm

  • Use private key to sign the token
  • Use public key to verify the token
  • Eg: RS, PS, ES

JWT 的優點

  • 因為 Server 不必儲存 JWT 所以一組 client 的 JWT 可以在多個不同的 Server 使用

JWT 的問題

  • 提供開發者已經過時的演算法
  • 竄改 header algorithm (So server should always check the header before verify the token)

References

[1] Web Dev Simplified (2019). What Is JWT and Why Should You Use JWT

--

--

R4 Cheng
R4 Cheng

Written by R4 Cheng

「0」が過去で「1」が未来「今」は何処にもない

No responses yet