十分鐘快速入門JWT

JWT 即 JSON Web Token,是為了在網絡應用環境間傳遞聲明而執行的一種基于JSON的開放標準((RFC 7519).該token被設計為緊湊且安全的,特別適用于分布式站點的單點登錄(SSO)場景。

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.

JWT應用場景

Here are some scenarios where JSON Web Tokens are useful:

  • Authentication: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

  • Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties, because as they can be signed, for example using public/private key pairs, you can be sure that the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.

JWT的組成

JSON Web Tokens 由三部分組成:

  • Header(頭部)
  • Payload(載荷)
  • Signature(簽名)

JWT由上述三段信息構成的,將這三段信息文本用.鏈接一起就構成了JWT字符串,如下:
xxxxx.yyyyy.zzzzz

Header

JWT的頭部由兩部分信息組成:

  • token的類型,這里是JWT
  • 使用的hashing 算法,例如HMAC SHA256 或者 RSA

完整的頭部就像下面這樣的JSON:

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

載荷就是存放有效信息的地方,這些有效信息包含三個部分:

  • 保留的聲明,例如:iss (issuer), exp (expiration time), sub (subject), aud (audience), and others。
  • 公共的聲明,可以添加任何的信息,一般添加用戶的相關信息或其他業務需要的必要信息,但不建議添加敏感信息,因為該部分在客戶端可解密。
  • 私有的聲明,是提供者和消費者所共同定義的聲明

一個payload示例如下:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

Signature

JWT的第三個部分簽名 需要將base64UrlEncode(header) 和base64UrlEncode(payload)使用.連接組成的字符串,然后通過header中聲明的加密方式進行加鹽secret組合加密,原文如下:

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and > > sign that.

例如,使用HMAC SHA256,Signature計算如下:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

將這三部分用.連接成一個完整的字符串,構成了最終的JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.
TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

secret是保存在服務器端的,JWT是由服務器端生成并返回給客戶端的,secret就是用來進行JWT的簽發和JWT的驗證,所以,它就是你服務端的私鑰,在任何場景都不應該流露出去。

JWT如何工作的

一般是在請求頭里加入Authorization,并加上Bearer標注:

Authorization: Bearer <token>

服務端校驗token的合法性,如果驗證通過就會返回相應的資源。整個流程就是這樣的:

jwt-diagram.png

參考資料

https://jwt.io/introduction/

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容