Updated: 2018-09-26 02:21:10 CST +08

JWT - JSON Web Token

Purpose

Store data in client side, which could be read by can’t be modified.

  • Authentication
  • Authorization

Structure

base64(header).base64(payload).signature

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJEaW5vIExhaSIsInN1YiI6ImRpbm9zODAxNTJAZ21haWwuY29tIiwiYXVkIjoiZGlub2xhaS5jb20iLCJleHAiOjE1MzczNTcyNjIsImlhdCI6MTUzNzM1NzE2MiwidXNlcklkIjo4MDE1Mn0.YaLyoBs8z5Va7YsIQaC6uEZDw8GZHBiV_2hIUSVQYUs

{
    "alg": "HS256", // algorithm
    "typ": "JWT" // type
}

Payload

{
    "iss": "Dino Lai", // issuer
    "sub": "dinos80152@gmail.com", // subject
    "aud": "dinolai.com", // audience
    "exp": 1537357262, // expiration time
    "iat": 1537357162, // issued at
    "userId": 80152 // custom field
}

Signature

Encrypt by algorithm defined in header

HmacSHA256(base64(header)+"."+base64(payload), $secret)

Flow

ClientAuth ServerApplication Serverloginauthenticateget user idget JWT header{"alg": "HS256", "typ": "JWT"}base64 encode JWT headereyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9put user id in JWT payload{"iss": "Dino Lai", "sub": "dinos80152@gmail.com", "aud": "dinolai.com", "exp": 1537357262, "iat": 1537357162 ,"userId": 80152}base64 encode JWT payloadeyJpc3MiOiJEaW5vIExhaSIsInN1YiI6ImRpbm9zODAxNTJAZ21haWwuY29tIiwiYXVkIjoiZGlub2xhaS5jb20iLCJleHAiOjE1MzczNTcyNjIsImlhdCI6MTUzNzM1NzE2MiwidXNlcklkIjo4MDE1Mn0generate signature: HS256(base64(header)+"."+base64(payload), secret)lNSYE_dZuNPCjCf9ybMfIDiUJ4CXFZCqOn5zpJ5oqPYput it all together by [header].[payload].[signature]eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJEaW5vIExhaSIsInN1YiI6ImRpbm9zODAxNTJAZ21haWwuY29tIiwiYXVkIjoiZGlub2xhaS5jb20iLCJleHAiOjE1MzczNTcyNjIsImlhdCI6MTUzNzM1NzE2MiwidXNlcklkIjo4MDE1Mn0.YaLyoBs8z5Va7YsIQaC6uEZDw8GZHBiV_2hIUSVQYUsopt[ Generate JWT ]send cookie with JWTset-cookie: jwt=xxx, Http-only, max-age=...response with headerAuthorization: Bearer <jwt>alt[ cookie ][ header ]request with JWTcheck signature to prevent data tampergenerate signature by header and payload, is the same as request signature?check expirationcheck exp field in payloadcheck ownercheck aud field in payloadopt[ verify JWT ]401 UNAUTHORIZEDread user id from JWTalt[ is Fail ][ is OK ]ClientAuth ServerApplication Server

Comparison

Comparison JWT Cookie Session
Side Client Client Server
Visible
Tamper
Identify
additional resource spend computing for en/decode, encrypt diskIO or network IO

Reference