使用 JWTs 的好处:
- Stateless
- Difficult to Fake
- Popular and easily implemented across platforms
- Flexbile
Parts of a JSON Web Token
header.payload.signature
Including Data in Our JWT Payload
解释 Payload:
{
"user":"usr",
"school":"example",
"role": "rle"
}
This part is not secret. Since the JWT base-64 encoding can be easily decoded without any additional information. This data is easily accessible by anyone who has the JWT. For that reason, you should never store sensitive information like passwords within this data object.
By decoding our payload, we know the question of who. But we still have the question of do we trust this information. The information within the payload ultimately answers our question of who is making the request.
解释 Header:
{
"alg":"HS256",
"typ":"JWT"
}
Most commonly, the header includes something like an algorithm such as HS256.
解释 Signature:
function(header,payload,SECRET) = SIGNATURE
The goal of our signature is to verify that the information within the JWT has not been tampered with and came from a trusted source. To achieve this goal, we really need a function that will output a signature that depends on our header, our payload, and something we will be calling a secret.
A secret is essentially just a string that we store on our authentication service, and on this server that we’ll be validating the JWT. If the secret is not known by a third party, they cannot sign the information within their payload or header. If the payload or header changes within a JWC (JSON Web Certificate) signed by our authentication service, but the secret remains the same, our signature will still change.
Therefore, if a JWT that is signed on are Auth service does not contain the same signature when it assigned on our consuming API server, we know that data has been tampered with in transit.