JSON Web Tokens (JWT)

JSON Web Tokens (JWT) are a compact, URL-safe means of representing claims to be transferred between two parties. Here's an example of a JWT and a breakdown of its components.

Example JWT

A JWT consists of three parts: the header, the payload, and the signature. These parts are encoded as Base64Url strings and separated by dots (.). Here is an example of a JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Breakdown of the JWT

1. Header

The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.

Example header:

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

When Base64Url encoded, this header becomes:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

2. Payload

The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private.

Example payload:

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}
  • sub (subject): Identifier for the user.
  • name: Name of the user.
  • 1iat (issued at): Timestamp when the token was issued.

When Base64Url encoded, this payload becomes:

eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ

3. Signature

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.

For example, if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:

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

Given the secret your-256-bit-secret, the signature is generated as follows:

SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Complete JWT

Combining these three encoded parts results in the JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Verification

To verify the JWT, the recipient must:

  • Take the encoded header and payload.
  • Verify the signature with the given algorithm and secret.
  • Decode the payload to access the claims.

Summary

JWTs are used extensively in web applications for authentication and information exchange because of their compactness and security features when properly signed and verified.

json
encryption
digital-signature
hmac
sha256
website
security
single-sign-on
Software and digital electronics / IT
Posted by admin
2024-06-09 09:04
×

Login

No account?
Terms of use
Forgot password?