What are JWTs?
JWT (JSON Web Token) is a lightweight secure transmission method that can be used to transmit secure and reliable information between different systems, such as user authentication, authorization, and information exchange. JWT uses JSON format to encode and transmit information, and is used to securely transmit information between parties in the form of JSON objects. This information can be verified and trusted because it is digitally signed. JWT can be signed with a private key (using the HMAC algorithm) or with a public/private key pair using RSA
Structure of JWT
JSON Web Token consists of three parts, which are connected by dots (.). These three parts are: header (Header), load (Payload) and signature (Signature) .
head
The header contains the type of JWT and the algorithm used, for example:
{
"alg": "HS256",
"typ": "JWT"
}
load
The payload contains information in JSON format, for example:
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
sign
The signature is generated by digitally signing or encrypting the header and payload, for example:
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
Three-part encrypted combination
The header and payload are encoded with Base64 , and the signature is generated using the specified algorithm and key, generating a key like this
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTQ0ODc1OTIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Token-based authentication and server-based authentication
-
The client sends a POST request
-
Generate a JWT on the server side, including the header, payload and signature, where the header and payload are encoded using Base64, and the signature is generated using the specified algorithm and key.
-
Return the generated JWT to the client.
-
The client adds the JWT to the Authorization field in the HTTP request header in subsequent requests
-
The server checks the JWT signature and obtains the username from the JWT
-
The server sends a response to the client
Difference between JWT, SWT, Security Assertion Markup Language Token (SAML)
1. Short after json encoding
Since JSON is less verbose than XML , it is also smaller in size when encoded; making JWT more compact than SAML. This makes JWT a good choice for passing in HTML and HTTP environments.
2. High security
In terms of security , SWT can only be symmetrically signed by a shared secret using the HMAC algorithm. However, JWT and SAML tokens can also be signed using public/private key pairs in the form of X.509 certificates. However, signing XML with XML digital signatures without introducing obscure security holes is very difficult compared to the simplicity of signing JSON.
3. Easy mapping
JSON parsers are common in most programming languages because they map directly to objects, in contrast XML has no natural document-to-object mapping. This makes using JWTs easier than SAML assertions.