JWT

What is JWT

JSON Web Token (JWT) is a compact JSON object which is used for securely transmitting information between parties.

Typically, it is used in authentication to prove the user/client is valid, e.g. Single Sign On.

How do JWT work

If the user login success, then authentication server will return JWT and subsequent each request will send the JWT to target resource, the target server will check the JWT is valid or not.

Generally the JWT is sent in the Authorization header using the Bearer schema, like:

Authorization: Bearer <token>

If the token is sent in the http header, Cross-Origin Resource Sharing (CORS) won’t be an issue as it doesn’t use cookies.

JWT Structure

JWT looks like(without line break):

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

It consists of three parts separated by dots <header>.<payload>.<signature>.

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

It contains token type which is JWT and signing algorithm.

The header is Base64Url encoded.

payload

Payload contains claims.

There are three types of claims:

  1. Predefined claims
Claim Name Remarks
iss Issuer
sub Subject, to whom or to which application the JWT is issued
aud Audience
exp Expiration Time
nbf Not Before
iat Issued At, the time at which the JWT is created, allowing JWTs to be invalidated after a certain amount of time
jti JWT ID
exp Expiration Time
  1. Public claims

    They should be defined in IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.

  2. Private claims

Custom claims to share information between parties that agree on using them and are neither registered or public claims.

An example of payload could be:

{
  "sub": "123",
  "name": "test",
  "admin": true
}

The payload is Base64Url encoded too.

signature

JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

For example, if it is signed using a secret with algorithm, then:

signature=algorithm(<encoded header>.<encoded payload>, secret) .

The algorithm is defined in header and the secret is developer defined to help to encode them.

The signature is used to verify the message wasn’t changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.

JWT VS SWT VS SAML

SWT : Simple Web Tokens

SAML : Security Assertion Markup Language Tokens

SAML is xml format, so its size is larger than JWT.

SWT can only be symmetrically signed by a shared secret using the HMAC algorithm. However, JWT and SAML tokens can use a public/private key pair.

Written on April 16, 2019