Original link: medium.com/vandium-sof…

In this article, you will explain the basics of JSON Web Tokens (JWT) and why it should be used. JWT is an important part of ensuring trust and security in your application. JWT allows declarations such as user data to be represented in a secure manner.

To explain how JWT works, let’s start with an abstract definition.

JSON Web token (JWT) is a JSON object defined in RFC 7519 as a secure way to represent a set of information between two parties. The JWT consists of a header, payload, and signature.

Simply put, JWT is just a string with the following format:

header.payload.signature
Copy the code

It should be noted that double-quoted strings are considered valid JSON objects.

To illustrate how and why JWT is actually used, we’ll use a simple example (see figure below). The three distinct entities in this example are the user, the application server, and the authentication server. The authentication server will provide JWT to the user. With JWT, users can securely communicate with applications.

How does an application use JWT to verify the user’s authenticity

In this example, the user first uses the authentication server’s login system to log in to the authentication server (for example, username and password, Facebook login, Google login, and so on). The authentication server then creates the JWT and sends it to the user. When the user makes an API call to the application, the user passes the JWT along with the API call. In this example, the application server will be able to verify that the incoming JWT was created by the authentication server (the verification process will be explained in more detail later). When a user makes an API call with the additional JWT, the application can use the JWT to verify that the API call came from an authenticated user.

Now, you’ll take a closer look at JWT itself and how it is built and validated.

Step 1. Create the Header

The Header section of JWT contains information about how to calculate the JWT signature, and is a JSON object of the following form:

{
    "typ": "JWT"."alg": "HS256"
}
Copy the code

In the JSON above, the value of the “TYp” key specifies that the object is JWT, and the value of the “alg” key specifies the algorithm used to create the JWT signature. In the example, we use the HMAC-SHA256 algorithm, a hashing algorithm that uses a key, to compute the signature (more on that in Step 3).

Step 2. Create PAYLOAD

The payload part of the JWT is the data stored in the JWT. In our example, the authentication server creates a JWT that stores user information, specifically the user ID.

{
    "userId": "b08f86af-35da-48f2-8fab-cef3904660bd"
}
Copy the code

The data inside The payload is referred to as The “claim” of The token.

In our example, we put only one declaration into payload. You can add as many declarations as you need. JWT specifies seven official fields to choose from.

Iss (Issuer) : exp (expiration time) : expiration time sub (subject) : aud (audience) : NBF (Not Before) : iAT (Issued At) : Issue time JTI (JWT ID) : numberCopy the code

In addition to official fields, you can also define private fields in this section. 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 negatively impact performance and lead to delays.

Step 3. Create SIGNATURE

The signature is calculated using the following pseudocode:

// Signature Algorithm data = base64urlEncode(header) + ". + base64urlEncode( payload ) hashedData =hash( data, secret )
signature = base64urlEncode( hashedData )
Copy the code

What this algorithm does is base64URL encodes the headers and payload created in steps 1 and 2. The algorithm then uses dots (.) to the resulting encoded string. Join together.

In the example, header and payload are encoded by base64URL as:

// header
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
// payload
eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ
Copy the code

We then apply the specified signature algorithm with the key to the coded header and the coded payload added to the period, and obtain the hash data required for the signature. In our case, this means applying the HS256 algorithm on the data string and setting the key to the string “secret” to get the hashedData string. Then, by base64URL encoding the hashedData string, we get the following JWT signature:

// signature
-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM
Copy the code

Step 4. Combine the three parts of the JWT

Now that we have created all three components, we can create the JWT. Bearing in mind the header.payload-signature structure of JWT, we just need to combine the above three parts and use dot (.). Separate them.

// JWT Token
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ.-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM
Copy the code

You can try creating your own JWT via jwt. IO.

Returning to our example, the authentication server can now send this JWT to the user.

How does JWT protect our data?

Understand that the purpose of using JWT is not to hide or obscure the data in any way, but to prove that the data being sent was created by a genuine source.

As shown in the previous steps, the data within JWT is encoded and signed, not encrypted. The purpose of encoding data is to transform the structure of data. Signed data allows the data sink to verify the authenticity of the data source. Therefore, encoding and signing data does not protect the data. On the other hand, the primary purpose of encryption is to protect data and prevent unauthorized access. See this article for a more detailed explanation of the difference between encoding and encryption.

Because JWT is only signed and encoded, and because JWT is not encrypted, JWT cannot guarantee the security of sensitive data.

Step 5. Verify JWT

In our example, 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 its authentication process, the application server receives the key from the authentication server. Because the application knows the key, when the user makes an API call to the application with JWT attached, the application can perform the same signing algorithm as step 3 on JWT. The application can then verify that the signature obtained from its own hash operation matches the signature on the JWT itself (that is, it matches the JWT signature created by the authentication server). If the signatures match, the JWT is valid and the API call came from a trusted source. Otherwise, if the signatures do not match, the JWT received is invalid, which could be an indication of a potential attack on the application. 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 trust between an application and its users. This is a starting point for understanding the basics of JWT and where it can be useful. JWT is just one of the challenges of ensuring trust and security in your applications. 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 way, except with an asymmetric algorithm (such as RS256) where the authentication server has a key and the application server has a public key. See this Stack Overflow problem for a detailed breakdown of the differences between using symmetric and asymmetric algorithms. It should also be noted that the JWT should be sent over an HTTPS connection. Having HTTPS helps prevent unauthorized users from using it to steal the JWT being sent and thus intercepting communication between the server and the user. In addition, it is important to set short expiration times in JWT, so that if old JWTS are misappropriated, they are considered invalid and can no longer be used.


IVWEB Technology Weekly shocked online, pay attention to the public number: IVWEB community, weekly timing push quality articles.

  • Collection of weekly articles: weekly
  • Team open source project: Feflow