Skip to content

Instantly share code, notes, and snippets.

@ZapDos7
Created February 16, 2024 00:20
Show Gist options
  • Save ZapDos7/8fd2e5a1725e83c3119d7d112cc69df9 to your computer and use it in GitHub Desktop.
Save ZapDos7/8fd2e5a1725e83c3119d7d112cc69df9 to your computer and use it in GitHub Desktop.

JWT (JSON Web Token)

  • is an open standard that defines a compact & self contained way for securely transmitting information between parties as a JSON object
  • digitally signed → verified → trusted
  • signed:
    • secret key (HMAC)
    • public/private key (RSA, ECDSA)

Types

  • signed tokens: verify the integrity of claims contained in it
  • encrypted tokens: hide those claims from other parties

Uses:

  • Authorization (log in: the REST requests include the token. Also, SSO)
  • Information Exchange: secure info transmission, verify content hasn't been tampered

Structure

header.payload.signature

Header & payload are JSON → base64URL encoded

  • header
    • typically
    "typ" : "JWT",
    "alg" : "x"
    
    where alg field refers to the singing algorithm used, e.g.: HMAC, SHA256, RSA
  • payload
    • contains claims like statements about user
    • 3 types:
      • registered: recommended to provide a set of useful, crosfunctional claims: in 3 chars
        • iss (issuer)
        • exp (expiration time)
        • sub (subject)
        • aud (audience)
      • public: defined at will or as a URI that contains a collision resistant namespace
      • private: custom, neither registered nor public info, agreed to be shared by parties
    • readable by anyone
  • signature: algo{based64URLEncoded(header)+"."+based64URLEncoded(payload), secret}

How they work

User logs in successfully, call returns JWT (aka credentials - must! security! - don't keep tokens longer than required, don't share sensitive session data)

User wants to access protected route/resource: header: Authorization: Bearer <token> (can be stateless).

Based on this authorization mechanism, server's protected routes will check for valid JWT in header. If it exists, user is allowed in.

CORS

Cross Origin Resource Sharing: if token sent in Auth, okay (no cookies)

+---------------------------+                +----------------------+            +----------------------+
|                           |                |                      | ---(1)---> |                      |
| Resource Server (our API) |    <---(3)---  | Application (client) |            | Authorization Server |
|                           |                |                      | <---2----- |                      |
+---------------------------+                +----------------------+            +----------------------+

Benefits

  • with signed tokens: no secret info (they can't be edited but they are visible)
  • less verbose
  • smaller after encoding
  • more secure
  • easier mapping
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment