# JWT Handbook Synthesis

## Intro

JWT = JWS (JSON Web Signatures) + JWE (JSON Web Encryption)

### Claims 

Definitions / Assertions about a party or object. Some part of the specs, some user defined.
JWT Standardizes commonly used claims (i.e. establishing identity).

### Purpose

Transfer claims between two parties in a standardized, simple way. Common usage : 
* Authentication
* Authorization
* Federated Identity
* Client-side sessions (stateless sessions)
* Client-side secrets

## JWT in Detail

A JWT contains : 
* Header (JSON object)
* Payload (JSON object)
* Signature/Encryption (dependant on signing/encryption algorithm)
Can be encoded in **compact representation** &rarr; JWS/JWE **compact serialization**. It is a Base64 URL-Safe encoding of the Header and Payload. The JWT is the concatenation of the the encoded Header, Payload and Signature, separated by a point. For instance : 

```
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
```

### Header

Contains claims about the JWT itself. Encrypted JWT Headers carry infos about the cryptographic algorithm.
Fields : 
* `alg` : the main algorithm used for signing and/or decrypting the JWT. (`none` for unencrypted JWT but still mandatory).
* `type` : Media type of the JWT. Should be `JWT`
* `cty` : Content type. Required for nesting JWTs. Must not be set otherwise.

User defined claims can be added to the header. Rarely used.

Exemple of header for an unencrypted JWT : 
```json
{"alg":"none"}
```
Encoded (in URL-safe Base64) to : `eyJhbGciOiJub25lIn0`.

### Payload

Where the user data is usually added. Certain claim from the spec may also be present. No claim are mandatory but certain have specific meaning. Such claims are **registered claims**.

#### Registered Claims

* `iss` : issuer. String/URI to uniquely identifiy the party that issued the JWT.
* `sub` : subjet. String/URI to uniquely identify the party that the JWT carries infos about.
* `aud` : audience. String/URI/Array of sych to uniquely identify the recipients of this JWT. &rarr; When this claim is define, the party reading the data must find itself in the `aud` claim or ignore the data. 
* `exp` : expiration. A number representing a specific date and time in the POSIX timestamp format. Represents the moment from which this JWT is considered invalid.
* `nbf` : not before. Opposit of `exp` claim. A number representing a specific date and time in the POSIX timestamp format. Represents the moment from which this JWT is considered valid.
* `iat` : issued at time.  A number representing a specific date and time in the POSIX timestamp format. Represente the moment at which the JWT was issued.
* `jti` : JWT ID. A string representing an unique identifier for this JWT. May be used to differentiate JWTs.

Names are short because JWT should be as short as possible.

#### Public and Private Claims

All claims that are not of the **registered claims** are either public or private.

* Private : Defined by user (consumer and producers). Used for particular application-specific uses. Care must be taken to prevent collision.
* Public : registered with IANA JSON Web Token Claims registry (registry fir users to register their claims to prevent collision) or named using a collision resistant name (with namespace).

### Unsecured JWTs

Exemple of unsecured JWT : 

Header :

```json
{
    "alg":"none"
}
```
Payload : 
```json
{
    "sub":"johnN7",
    "session":"zehudezyg347tdyeyzde",
    "name":"John Shepard",
    "lastpage":"/"
}
```

No signature / encryption, so the JWT is encoded as two elements : 

```
ewogICAgImFsZyI6Im5vbmUiCn0K.
ewogICAgInN1YiI6ImpvaG5ONyIsCiAgICAic2Vzc2lvbiI6InplaHVkZXp5ZzM0N3RkeWV5emRlIiwKICAgICJuYW1lIjoiSm9obiBTaGVwYXJkIiwKICAgICJsYXN0cGFnZSI6Ii8iCn0.
```

![Unsecure JWT](images/unsecure.png)

Unsecured JWT are rarely used.

## JSON Web Signatures

### Structure of a Signed JWT

Signed JWT Carry a signature after the last dot (`.`) in the compact serialization form. Several type of signing algorithms are available : 
* HMAC SHA-256 (HS256) *- preferred*
* RSASSA PKCS1 v1.5 SHA-256 (RS256) *- recommended*
* ECDSA P-256/SHA-256 (ES256 *- recommended*)

### Compact Serialization

![Signed JWT](images/signed.png)

### Algorithms

#### HS256

HMAC is an algorithm that combines a payload with a secret using a cryptographic hash function (SHA-256). The result can be used to verify a message only if both the generating and verifying parties know the secret. HMAC allows messages to be verified through shared secrets.

#### RSASSA

Variation of the RSA Algorithm, adapted for signature. The private key is used to to sign & verify the message, and a public key can be used to only verify the message. It allows **one to many** secure message distribution.

## JSON Web Encryption

JWS is for validating data. JWE keeps data unreadable to third parties. As JWS, JWE provides a shared secret scheme, which works like in JWS, and a public/private key scheme which works differently : public key holder encrypt data which is decrypted by private key holders.

### Structure of Encrypted JWT

A JWE Contains 5 elements : 
* Protected Header : header equivalent to JWS header
* Encrypted Key : Symetric key used to encrypt ciphertext.
* Initilization Vector : random data for encryption algorithm
* Ciphertext : Data being encrypted
* Authentication Tag : Additionnal data produced by encryption algorithm used to validate ciphertext against tampering.

