JWT tokens - AngularBuildUp/angular-microworkshops-authorization GitHub Wiki
Javascript web tokens are tokens that are exchanged by a web application for a protected resource. It is simply a JSON payload containing one or more claims. They carry a Message Authentication code (or MAC).
This promote stateless backend servers as there is no need to store tokens in-memory between requests. Also there is no need to store password digests at the level of application database either. They are a very secure because it is hard to forge them.
Their body has three parts:
- The Header
- The Payload
- The Signature
The header contains technical metadata information about the token itself, like the algorithm that is used for the signature. This is also a plain javascript object.
The payload is a plain javascript object.
The signature is a MAC (Message Authentication Code). It can only be produced by someone in possession of both the payload (plus the header) and a given secret key. This is produced from header and payload hashing (or encryption).
The JWT token Header and Payload are encrypted with Base64Url because we sometimes use the JWT token in a URL parameter, like in third-party login redirects to our site.
Types
There are two types of JWT tokens. Hashed SHA-256 and encrypted via RS256.
With SHA-256
We send the JWT back to the server. We hash the header and payload together with the secret key of the issuing server. Machines that are consuming the JWTs use the same secret key for validation and user identification. If it matches the signature then JWT token is valid.
With RS256
We use this alternative because hash algorithms can be brute forced if the input secret key is weak but also because of secret key distribution issues. If we want to change the password we have to have it distributed and installed to all network nodes that need it.
Now we are creating two keys instead of one. One private key, owned by the authentication server used only to sign JWTs, and a public key used by the application server only to validate JWTs.
In practice we take the header and payload and we hash them using SHA-256. We then take the hash output, encrypt it, instead of whole data) using the RSA private key, which gives us the RS256 signature. Receiver can take the header and payload, decrypt them with the public key, hash the header and payload and compare the hashed decrypted value.