JWT is a popular cross-domain authentication solution. Its principle is to encrypt user information to generate a Token. Each time the server requests a request, it only needs to use the saved key to verify the correctness of the Token, and there is no need to save it again. Any Session data makes the server stateless.
jwt verification method is to encrypt user information to generate a token. Each time a request is made to the server, it only needs to use the saved key to verify the correctness of the token. There is no need to Any session data is saved, and the server becomes stateless, making it easy to expand.
User information before encryption, such as:
{ "username": "vist", "role": "admin", "expire": "2018-12-08 20:20:20" }
Token received by the client:
7cd357af816b907f2cc9acbe9c3b4625
JWT structure
A The token is divided into 3 parts:
header
payload
Signature(signature)
The three parts are separated by ".", such as:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Header
JWT The header part is a JSON object describing metadata, usually:
{ "typ": "JWT", "alg": "HS256" }
typ is the declaration type, specify "JWT"
alg is the encryption algorithm, the default is "HS256"
Load
The payload is the carrier of data, used to store the actual data information that needs to be transmitted, and is also a JSON object.
JWT official recommended fields:
iss: jwt issuer
sub: jwt for users
aud: The party receiving jwt
exp: The expiration time of jwt, this expiration time must be greater than the issuance time
nbf: Define the time before which the jwt is unavailable.
iat: The issuance time of the jwt
jti: The unique identity of jwt, mainly used as a one-time token to avoid replay attacks.
You can also use custom fields, such as:
{ "username": "vist", "role": "admin" }
Signature
The signature part is a comparison of the first two parts (header part, payload) to prevent data tampering.
Follow the following steps to generate:
1. Specify the secret first
2. Convert the header and payload information to base64 respectively
3. Use the algorithm specified in the header to encrypt
Finally, signature = HMACSHA256(base64UrlEncode(header) "." base64UrlEncode(payload),secret)
The signature obtained by the client:
header.payload.signature
The JWT can also be re-encrypted.
Recommended tutorial: "PHP"
The above is the detailed content of What does JWT do?. For more information, please follow other related articles on the PHP Chinese website!