JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between parties as JSON object.
It is compact, readable and digitally signed using a private key/ or a public key pair by the Identity Provider(IdP). So the integrity and authenticity of the token can be verified by other parties involved.
The purpose of using JWT is not to hide data but to ensure the authenticity of the data. JWT is signed and encoded, not encrypted.
JWT is a token based stateless authentication mechanism. Since it is a client-side based stateless session, server doesn‘t have to completely rely on a datastore(database) to save session information.
A JSON Web Token consists of 3 parts separated by a period.
header.payload.signature
JWT header consists of token type and algorithm used for signing and encoding. Algorithms can be HMAC, SHA256, RSA, HS256 or RS256.
{
"typ": "JWT",
"alg": "HS256"
}
Payload consists of the session data called as claims. Below are some of the the standard claims that we can use,
{
"sub": "user10001",
"iat": 1569302116
}
Custom claims can also be included in the claim set. When using custom claim sets,
{
"sub": "user10001",
"iat": 1569302116,
"role": "admin",
"user_id": "user10001"
}
Signature is most important part of a JSON Web Token(JWT). Signature is calculated by encoding the header and payload using Base64url Encoding and concatenating them with a period separator. Which is then given to the cryptographic algorithm.
// signature algorithm
data = base64urlEncode( header ) + "." + base64urlEncode( payload )
signature = HMAC-SHA256( data, secret_salt )
So when the header or payload changes, signature has to calculated again. Only the Identity Provider(IdP) has the private key to calculate the signature which prevents the tampering of token.
Basically the identity provider(IdP) generates a JWT certifying user identity and Resource server decodes and verifies the authenticity of the token using secret salt / public key.
Just like any other authentication mechanism, JWT also has its own pros and cons.
How JWT (JSON Web Token) authentication works?
原文:https://www.cnblogs.com/Griffin/p/15097374.html