Site icon Adron's Composite Code

JSON Web Tokens

JSON Web Tokens, one hears all about them all the time. But what exactly are they? I’ve used them a thousand times myself but I never really checked out exactly what they are. So this post fills that gap for me, and hopefully it’s useful to a few of you readers out there too.

What is a JSON Web Token?

JSON Web Token, or JWT, is open standard RFC 7519 for compact and self-contained secure information transmission between two parties using JSON objects. For a refresher, JSON stands for JavaScript Object Notation. JWTs provide security between parties by being signed, which can be used the verify the integrity of the claims contained. JWTs can be signed using a secret or a public / private key pair using RSA or ECDSA. JWTs can also be encrypted to hide those claims as well.

What are JWTs good for? When should you use a JWT?

The most common, and what I’ve found the most recommended use of JWTs, is for API authentication or server-to-server authorization.

JWT Structure

Paraphrased and summarized using the Wikipedia example here.

The header identifies which algorithm generated the signature, such as HMAC-SHA256, as indicated in the example below.

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

Then the contenxt, or payload, contains the claims. There are seven Registered Claim Names (RCN) as standard fields commonly included in tokens. Custom claims can also be included, the following is the At Time claim, designated iat and custom claim of loggedInAs. The others include: iss (issuer), sub (subject), aud (audience), exp (expiration time), nbf (not before time), iat (issued at time), and jti (JWT ID). For these and many other claims the IANA has a resource here.

{
  "loggedInAs": "admin",
  "iat": 1422779638
}

The signature securely validates the token. It’s calculated through encoding the header and payload using Base64url encoding per RFC 4648 and concatenated with a period as the seperator. This string is run through a cryptographic algorithm specified in the header (i.e. HMAC SHA 256). A function signature would look something like this.

HMAC_SHA256(
  secret,
  base64urlEncoding(header) + '.' +
  base64urlEncoding(payload)
)

All concatenated together the token would then look like this.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI

Do and Do Nots

Exit mobile version