What is Authentication (JWT, JWS, JWE)?

User authentication is very important in the digital world. JWT, JWS, JWE 3 are famous tools for determining and verifying the identity of users in cyberspace and websites. The user authentication process, or user validation, is usually performed in two forms. Either by sending cookies per request or sending a signed token against any request submitted by the user. I will talk toyou about authentication via JWT or JSON Web Token, JWS or JSON Web Signature, as well as JWE or JSON Web Encryption in this article.

User Validation Methods with JWT

We said that the user authentication process, or user validation, is usually done in two forms. The first form, or Cookie-Based Authentication, is a more popular method. In this method, after each user’s request, a cookie is sent to the server for user authentication, and again a cookie is sent from the server to the client to verify the identity of the user. In the second form or Token-Based Authentication, after each user request, a signed token is sent to the server in order to authenticate the user.

Advantages of Token-Based Authentication Method

This method may be less popular, but it has some advantages than the cookie-based method.
Cross domains Cross-domain /CORS: CORS and cookies don’t have much compatibility. This is because the issuance of each cookie depends on its second export, and it is not acceptable to use it in the rest of the second. If in tokens, the initial issuance is not dependent on the issuance of the second and the authenticity of the token is confirmed based on the encryption methods.

Server-side scalability without being:

The token entity is self-contained, which means that you do not need to store information in a session on the server side when you are working with tokens, and all of this information is stored in client-side cookies or local storage.

Distributing the program by CDN:

When you work with Token, you can download all program files such as JavaScript files, images, etc. by CDN. In this situation, server-side codes are merely a typical API.

No entanglement of codes on the client and server side:

If we use tokens, this token has the ability to be exported in any program and anywhere, and there is no need to create any dependencies between the codes on the server side with client-side codes.

Better compatibility of Token with mobile operating systems:

If you want to develop apps related to different mobile platforms, you’d better use tokens instead of cookies. Because cookies don’t work well when working with APIs on the server side, and in this case, tokens work better.

CSRF bug:

Because of your use of tokens instead of cookies, CSRF attacks will no longer happen. Because in practice, cookies will no longer be sent to the server where there is any possibility of misuse of an authenticated cookie to issue requests similar to the request of the person who logged in to the site.

Better performance:

Tokens do not require much to go back to the database due to their self-inclusion nature, hence the speed of operations using them increases.

Make it easier to write integration tests:

When you use tokens, you don’t need to go through the login screen to run any of the integrity tests in your app and will run much easier than other scenarios.

Standardization:

Using JWT for you means working with different types of libraries and platforms.

What is JWT?

If we want to explain JWT in general, we have to say that JWT is a kind of web standard. This standard introduces a compact and self-inclusive way to transfer information securely and between different purposes using a JSON object. Transferable information is reliable because all of them have digital signatures. All JWTs can be signed by a pair of public and private keys created by the RSA algorithm and a private key created by the HMAC algorithm. If we want to explain more about self-inclusive and intensive words, we can say that:
Self-inclusion means that in this token, payload or useful load contains all the information needed to validate and authenticate a user. In this case, the query is taken only once from the database.
Being compact also means that the JSON object in JWT has a small size. As a result, it can easily be sent via an HTTP Header or POST parameters or by a URL, and the process of sending it will also be faster because the JSON object size is small.
In Persian, JWT is also called jute. All jutes are composed of three parts, each of which is separated from the other by one point. Like xxxxx.yyyyyy.zzzzz. These three sections are header, payload and signature, each of which will be inked by base64 algorithm. Below you can see an example of a JWT token.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.XbPfbIHMI6arZ3Y922BhjWgQzWXcXNrz0ogtVhfEd2o

Header Episode

This section itself consists of two parts based on which the type of token and the type of algorithm that token used is specified. Here is our JWT token type. The algorithms used by Token are HMAC SHA256 and RSA. Below, you will see the decrypted information from the header section.
{
   "alg": "RS256",
   "typ": "JWT"
}

Payload Episode

This section contains claims. claims are information about our desired entity, for example the user, as well as some additional meta-data. claims are three types that include:

First type Reserved claims:

This type includes some useful information as well as pre-specified and non-compulsory information. Information such as exp or expiration date, iss or exporter, sub or subject (title) and aud or audience (contact).

The second type of Public claims:

This type includes information previously recorded by IANA JSON Web Token Registry and whose naming spaces do not interfere with each other.

Third type Private claims:

This type includes a custom request used to transfer data between different destinations.
Below, you’ll see information from the payload section.
{
   "exp": 1520507268,
   "sub": 582946,
   "name": "ErFUN KH",
   "admin": true
}

In this example, the 2 data listed in the first code are reserved claims. Also, the last 2 data are private claims.
Payload of reserved claims type includes:

Iss or issuer section:

In this section, the token exporter must be specified. For example, you can set the “hesabfun.com” value for it.

Sub or subject section:

In this section, the main theme of token is specified. For example, our token issue relates to identifying users. For this purpose, we can use the id placement of users in token. In this way, we will find out which user the token is from.

Aud or audience section:

In this section, the location of the token usage is specified. The audience section is mostly used when we have multiple servers and all have a private key for digital signature. For example, you can set a “https://blog.hesabfun.com” value for it.

Exp or expiration section:

In this section, the validity time of the token is specified. This time should be specified in the form of Unix time.

nbf or not before section:

In this section, the issue of when token processing will be possible is determined.

iat or issuedAt section:

In this section, the token construction date should be brought in the form of Unix time.

Jti or JWT jid section:

In this section, for each token, an exclusive ID is specified. This is the case in both telegram messenger token management system and microsoft list. In this case, it is better not to upload the whole ID into the database and only sub and exp are used.

signature section

So far, you’ve seen that all the data that had algorithm 64 was inked and easily decoded in any system, and each person would be able to make the token and send it, of course, without signature.
As you can see in the photo, the Header and payload sections are assembled together and encrypted by a private key located solely on the server. This section is generally used for signature or signature. The information in the payload section should not be changed because in case of any changes, it no longer has a signature for the credit server and since the user does not have access to the private key, he will not be able to generate the token. Be careful that vital information such as cipher and … It should not be placed inside the token because it is easy to read, but if it is necessary, it is necessary to use JWT.

How to use JWT in apps

When the user is logged on by a successful login, the server issues a secure token in JWT format and sends it to the user. This token must necessarily be stored locally on the client side, which is usually done in local storage. It is recommended that you do not use cookies because we will explain that cookies have security problems. After saving this token, no sessions will be made on the server for each user and no cookies will be sent to the user from the server.
In this case, if the user wants to access a protected content or page, it is necessary to send his token to the server. This is done by a custom Authorization header, along with Bearer schema, which is similar to the following example:
Authorization: Bearer <token>
This method of authentication is stateless. This is also because the user status is never stored on the server side. In fact, the server-side API firstly searches the above Authorization header in the incoming request. If this search is successful and its authenticity is verified, the user will be allowed access to the protected resource. As explained in previous sections, due to the inclusion of tokens, all the information needed to allow user access is located in tokens and there is no need to go back to the database and this will speed up the work.

JWT Storage Location

Usually, JWTs are stored in the local storage of each browser. This is often the case, but you should keep in mind that local storage is actually a sandbox that is limited to the second current program and, for example, cannot be accessed through its subdomains. In this case, it is better to store JWTs in cookies. This is because cookies are also stored on the client side and do not have restrictions on storing JWTs in the local storage of any browser. Of course, you should consider that the volume of cookies can be up to 4 KB, and if the claims stored in a JWT are increased and encoded, this volume will be greater than 4 KB. Of course, you can save JWTs in each browser’s session storage as well. The only problem with this is that as soon as the browser closes, these tokens will be erased. If you use local storage to store JWTs, other Cross Site Request Forgery attacks have no effect. If you use cookies to store tokens, these attacks will be possible. The solution to this is to consider the expiration date of the tokens as closely as possible, which can be used faster if disclosed.

Expiration and re-issuance of tokens

If the tokens are stateless, they can only operate based on checking the signature of each message. This means that this activity may last forever. This is usually considered a problem and it is necessary to specify an expiration date or exp for the token to solve it. If your app is sensitive, this expiration date can be 15 minutes or less. And if the program is less sensitive, this time can be increased for a few months. You may be wondering what to do if we want to disable Tokeni in real time? In response, I have to say that one of the ways you can do this is to store records of all tokens in a database. You can use a jti field to do this. In this case, the ids will be stored in the database. You will be able to communicate between users and their information and exported tokens. In addition to checking the token signature, the app will also be able to refer to the list of these ids and implement additional authentication for faster cancellation of tokens.

How can we provide the most security for JWTs?

To do this it is necessary to:
  1. Sign all your tokens with a strong key. Note that this key should be stored only on the server, not elsewhere. In this case, when the server receives a token from the user, the validity of the message signed to the server is measured by the server based on the strong key on it.
  2. If you have stored sensitive and specific information in tokens, you should use JWE or JSON Web Encryption. This is because JWTs only have digital signatures and are not encrypted.
  3. For more security, you need to send tokens solely through the HTTPS protocol.
  4. If you use cookies to store tokens. You should only use Secure to get rid of Cross-Site Scripting XSS attacks.
  5. Consider the expiry date of the issued tokens in a principled and logical manner.

And in the end,

Mirbazorgi’s website aims to help you learn and fix your problems by providing articles and practical experiences. Email me if you have any questions.