Five Steps to Understanding JSON Web Tokens (JWT)
Easy Steps to Understand JSON Web Tokens (JWT)
In this article we will cover: What is the rationale behind JSON Web Token(JWT) and why do we use it? JWT is an important part of ensuring that our applications are trusted and secure. JWT allows us to represent declarations like user data in a secure way.
To explain how JWT works, let’s start with an abstract definition.
JSON A Web Token is a JSON object. Defined in REC 7519, it represents a set of secure information modes for both parties. It consists of a header, payload, and signature.
In simple terms, JWT is a string of the form,
header.payload.sinagure
Copy the code
It should be noted that strings with double quotes (” “) are considered valid JSON objects
To show how and why we use it, I’ll use three simple entity examples (see figure below).
The three instances are the user, the application server, and the authorization server. The authentication server will provide the JWT to the user, with which the user can securely communicate with the application server.
In this example, the user first uses the authentication server’s login system to log in to the authentication server. (for example: username, password, Facebook, Google login). The authentication server is then authorized to create the JWT and send it to the user. When there is an API call between the user and the application, the user passes the JWT in the process. In this step, the application server verifies that the JWT being passed was created by the authentication server. (More on the verification process later). Therefore, when an API call is made between a user and an application using the carrying JWT, the application can use the JWT to verify that the API call came from an authenticated user.
Next, we will take a closer look at the construction of JWT and its verification methods.
Step 1. Create the HEADER
The header of the JWT contains information about how to calculate the JWT signature. The header is a JSON object formatted as follows
{
"typ": "JWT"."alg": "HS256"
}
Copy the code
In this JSON object. The value of the TYP key indicates that the object is JWT, and the value of alG indicates the hash algorithm used to create the JWT signature. In our example, we use the HMAC-SHA256 algorithm, a hash algorithm that uses a key, to generate the signature (we’ll discuss this in more detail in Step 3).
Step 2. Create the PAYLOAD
The payload is also part of the JWT and is used to hold the data in the JWT (also known as the ‘declaration’ of the JWT). In our example, the authentication server creates a JWT and stores the user’s information in it, especially the user ID.
{
"userId": "b08f86af-35da-48f2-8fab-cef3904660bd "
}
Copy the code
In our example, we put only one field in the load. You can add as many fields as you need.
JWT has several standard official fields like “ISS “(issure) : issuer, “sub”(subject) : subject, and” exp “(expiration time) : expiration time. These fields are useful when creating a JWT, but they are optional. For a list of JWT standard fields, see Wikipedia
Keep in mind that the size of the data will affect the overall size of the JWT, which is usually not a problem, but too large a JWT can have a negative impact and lead to delays.
Step 3. Create SINATURE(signature)
The signature is implemented with the following pseudocode:
// Signature algorithmData = base64urlEncode (header) + ". + base64urlEncode (payload) hashedData = Hash (data, secret) signature = base64urlEncode (hashedData)Copy the code
What this algorithm does is base64URL encoding with the headers and payload created in steps 1 and 2. The encoded strings produced by the algorithm are then linked with a ‘.’ between them. In our pseudocode, the linked string is placed in the data. This string is used in the JWT header to specify the key for the hash algorithm. The generated hashData will be assigned to hashData. The hashData will then be base64url encoded to produce the JWT signature.
In the example, the header and payload are base64URL-encoded as follows:
// header
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
// payload
eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYZOTA0NjYwYmQifQ
Copy the code
Then, a signature algorithm with a specified key is applied to periodically encoded headers and payloads. In our case, this means using the HS256 algorithm specified in the Header on the data and setting the key to the string ‘secret’ to get the hashData string. After hashData is base64URL encoded, we get the following JWT signature:
// signature
-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM
Copy the code
Step 4. Combine the three parts of the JWT.
So far we have generated the three components of JWT. Remember the structure of JWT: header.payload-signature
We simply connect the three parts with a ‘.’. We use the base64URL-encoded header, payload, and signature from step 3 to form the JWT below
// JWT Token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ.-xN_h82PHVTCMA9v doHrcZxH-x5mb11y1537t3rGzcMCopy the code
You can try creating your own JWT in your browser via jwt. IO
Returning to our example, the authorization server can now send the JWT to the user.
How JWT keeps our data secure.
It is important to understand that our purpose in using JWT is not to hide data in any way. It is used to verify that the data we receive comes from a real data source.
As we showed in the previous steps, the data in JWT is encoded and signed, not encrypted. The purpose of encoding data is to transform data structures. Signing data allows the data receiver to verify the authenticity of the data remote. Therefore, encoding and signing data does not protect the data. Encryption, on the other hand, is primarily intended to protect data from unauthorized access. See this article for a more detailed explanation of the difference between encoded and encrypted, and how hashing works
Because JWT is only encoded and signed and is not encrypted, JWT does not guarantee the security of sensitive data
Step 5. Verify JWT
In the simple three entity cases above, we use JWT signed by the HS256 algorithm, where only the authentication server and the application server know the key. When an application sets up the authentication process, it receives a key from the authorization server. Because the application server knows the key, when a user makes an API call to the application with JWT, the application can use the same signing algorithm as in Step 3. The application server can then verify that the signature obtained from its own hash operation matches the signature on the JWT itself. (that is, whether it matches the JWT signature created by the authentication server). If the signatures match, the JWT received is valid, indicating that the API call came from a trusted source. In addition, if the signatures do not match, the JWT received is invalid, which may indicate that the application may have been potentially attacked. Thus, by validating JWT, the application adds a layer of trust between itself and the user.
conclusion
We learned what JWT is, how to create and validate them, and how to use them to ensure prior trust between the application and its users. This is the beginning of understanding the basics of JWT and its usefulness. JWT is just one of the challenges of ensuring trust and security in your application.
It should be noted that the JWT authentication setup described in this article uses a symmetric key algorithm (HS256). You can also set up JWT authentication in a similar manner, unless you use an asymmetric algorithm (RS256) and the application server has a public key. Take a look at this question on Stack OverFlow to see the difference between using symmetric and asymmetric algorithms.
It should also be noted that JWT should be an HTTPS connection (not HTTP). The HTTPS connection helps prevent unauthorized users from using it to steal the sent JWT, thus preventing others from intercepting the server’s previous communication with the user.
In addition, payoad(payload) in JWT sets the expiration time, especially the payload(payload) with a short expiration time. This way, if old JWT are attacked, they will be invalidated and can no longer be used.
If you enjoyed this article and are working on AWS Lambda and using JWT, check out our project: Vandium
Mars Reed Technology Web front-end development engineer likes to watch movies, masturbate and learn. Good at wechat small program development, system management background. Visit www.talkmoney.cn to learn more.
Author home Page:
github
segmentfault