What is Authentication (JWT, JWS, JWE)?

In today’s world, user authentication is very important. JWE 3, JWS, and JWT are some of the most popular tools that can be used to authenticate users in cyberspace and websites.  Note that the authentication process, in other words, user authentication, is usually done in two ways.  This process is done either by sending cookies for each request or by sending a signed token in response to each request submitted by the user.  My name is Arsalan Mirbozorgi. In this article I am going to tell you about authentication via JWT, JWS, JSON Web Token, or JSON Web Signature and JWE or JSON web encryption.

User Validation Methods with JWT

We have already told you that the authentication process is done in two ways. The primary method or the cookie-based Authentication is a relatively popular method. Note that in this method, after the user sends a request, a cookie is sent to the server for user authentication. A cookie is then sent from the server to the client to authenticate the user. In the second case, or Token-based Authentication after each request of the user, a signed token is sent to the server for user authentication.

Advantages of Token-Based Authentication Method

Note that this method may be less popular than the method of using cookies, but it has various advantages over that method, which we will mention below.

Cross domains CORS / cross-domain and cookies are not so compatible with each other. The reason for this is that the issuance of each cookie depends on the domain of its issuance, and in addition, its use in other domains is not acceptable. Note that in the case of using tokens, the initial issuance is not dependent on the issuance of the skirt, and also the authenticity of the token is verified using encrypted methods.

Server-side scalability without being:

Note that the existence of the token is self-contained. This means that you do not need to store information in the server-side session while handling tokens. All information is stored in client-side cookies or Local Storage.

Distributing the program by CDN:

While you are working with the token, you have the ability to distribute all the various files in the program such as image files, JavaScript, and other items by CDN. In this case, the code that goes to the server is just a normal API.

No entanglement of codes on the client and server side:

If you use a token, this token gives you the ability to issue the required token in any program and any place, and there is no need to create dependencies between the code on the server side and on the client side.

Better compatibility of Token with mobile operating systems:

Using tokens instead of cookies is a better option if you want to develop applications in mobile operating systems. Cookies do not work well when working with AIP on the server side, and in this case, it is more  appropriate to use a token.

CSRF bug:

If you use a token instead of a cookie, CSRF attacks will not happen to you because no cookies will be sent to the server anymore, so it is possible to misuse the authenticated cookie to make similar requests to the person who logged in to the site. 

Better performance:

Tokens do not need to go back and forth to the database due to their inclusive nature, which is why their use speed is so much higher.

Make it easier to write integration tests:

When you use trusts, none of the program integration tests require you to go through your login page, and all of these activities are performed more easily.

Standardization:

Using JWT allows you to work with different types of libraries and platforms.

What is JWT?

If we want to explain what JWT is, we should say that JWT is a kind of web standard. JWT introduces a compact and self-contained way to transfer information securely between different destinations using a JSON object. Transferred information is reliable because it all has a digital signature. All JWTs can be signed by  public and private keys in paire generated by the RSA algorithm and a private key generated by the HMAC algorithm. If we want to explain more about self-contained and concise words, we can say that:

Self-inclusion means that in this token, payload contains about all the information needed for authenticating a user.  In this case, the query is taken from the database only once.

Self-contained means that the JSON object in the JWT is small. So, it can either be sent via an HTTP header easily or POST parameters or via a URL, and the transform process will be faster due to the small size of the JSON object.

In Persian, the JWT method is also called jute. All jutes have three parts, each of which is separated from the others by a point. Like xxxxx.yyyyy.zzzzz. These three sections are the header section, the payload section and the signature section, each of which will be encoded by the Base64 algorithm.  In the next picture you can see an example of a JWT token.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.XbPfbIHMI6arZ3Y922BhjWgQzWXcXNrz0ogtVhfEd2o

Header Episode

This section has two parts, the type of token and the type of algorithm used by the token are determined based on that.  Here our token type is JWT. The algorithms used by the token are also HMAC SHA256 and RSA.  In the next picture, you can see the information decoded from the header section. 

{
   "alg": "RS256",
   "typ": "JWT"
}

Payload Episode

This section contains claims. Claims are information that is related to our intended entity, for example the user, and some additional metadata. Usually there are three types of claims:

First type Reserved claims:

Reserved claims include some useful information and predefined and non-mandatory information.  Information such as exp or expiration date, iss or issuer, sub or subject (title) and aud or audience.

The second type of Public claims:

Public claims contain information previously registered by the IANA JSON Web Token Registry and which naming spaces do not overlap.

Third type Private claims:

Private claims include a special request that is used to transfer data between different destinations. In the next picture, you can see the encoded information from the payload section.

In this sample, the 2 data listed at the first of the code are reserved claims. Also, the last 2 data are of Private claims type.

{
   "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 the issuer section, the issuer of the token must be cleared. For example, you can use the value of “hesabfun.com”.

Sub or subject section:

In this section, the main subject of the token is identified. For example, the subject of our token is user identification. We can use the inclusion of user IDs in the token for this purpose. With that we will find out which user sent the token.

Aud or audience section:

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

Exp or expiration section:

In this part, the token validity time is specified. This time must be shown as Unix time.

nbf or not before section:

This part specifies when token processing will be possible.

iat or issuedAt section:

In this part, the token creation date must be given as Unix time.

Jti or JWT jid section:

In this section, a unique ID is selected for each token. This is the case with both the Telegram messenger token management system and the Microsoft list. In this case, it is better not to upload the entire ID inside the database and use only sub and exp.

signature section

Till now, you have seen that all the data that had the 64 algorithms was encoded and can be easily decoded in any system, and anyone can build and send tokens without a signature.

As you can see in the image above, the header and payload are integrated and can be encrypted with a private key that is only contracted into the server. Note that this entire section is used for the signature section, and the information contained in the upload section should not be changed in any way, because otherwise the signature written for the server is no longer valid and cannot be generated because the user does not have access to the private key. Note that vital information such as passwords, etc. should not be inserted into the token in any way as they can be read and used without any problems;  But if you really need to do this, you need to use JWT.

How to use JWT in apps

When a person logs in Successfully, the server issues a secure JWT token and sends it to the user. Note that this token must be stored locally on the client side, which is usually done in Local Storage. We recommend that you do not use cookies, as we will explain later that some cookies can be a security issue in a variety of areas. Once you have saved this token, no more cookies will be created for each user on the server and no cookies will be passed from user to user. In this case, if a user wants to access a secure page and content, he needs to send the token in person to the server. This can be done by a custom authentication header with a bearer schema, which you can see in the image below.

Authorization: Bearer <token>

Note that this method is for stateless authentication. This is because the user status of any user can never be saved on the server side.  In fact, the API address of the server in the header steps searches for the so-called authentication in the received request. If the result of this search is successful and its accuracy is confirmed, the user will be allowed access to various protected resources. As we explained to you in the previous sections, because tokens are self-contained, all the information needed to grant user access is contained in the token, and there is no need to go back to the database, which can speed up doing things.

JWT Storage Location

Note that Local Storage is actually the part where JWTs are usually stored in each browser.  Note that this is very efficient in most cases, but you should note that Local Storage is actually a kind of sandbox that is limited to the current domain of the program and through subdomains you cannot access them.  In this case, we recommend that you save the JWTs in cookies, so that cookies are also stored on the client side, and there is no restriction on storing JWTs in the local storage of any browser. Of course, you have to keep in mind that cookies can be up to four kilobytes in size at most, and if the claims stored in a JWT are encoded, the volume will exceed four kilobytes.  Of course, you can save JWTs in each browser’s session storage, but there is a problem with this, and the problem is that these tokens are completely deleted as soon as the browser is closed. If you use Local Storage to store JWTs, other cross site request forgery attacks will not affect your work. If you use cookies to store tokens, these attacks are completely possible, and the only solution is to consider the expiration date of the cookies as soon as possible so that you can use them faster if they are exposed.

Expiration and re-issuance of tokens

Note that if you use stateless tokens, you can only use their activity based on checking the signature of each message. That is, the activity has the ability to continue forever, and this is known as a problem. To solve it you need to set an expiration date for your token. if your program is very sensitive, this expiration date can be fifteen minutes or even less. If your program is less sensitive, you can increase this time to even a few months. You may be wondering what to do if you want to deactivate the token at the moment. To answer this question, we have to tell you that one of the ways you can help you do this is to store the records of all the tokens in the database. You can use a jti field to do this.  In this case, the IDs will be stored in full in the database you want. You have the ability to communicate between users and their information, and the issued capabilities. If you do this, in addition to checking the trust signature, programs will be able to refer to a complete list of these IDs and find additional authentication for faster revocation of tokens.

How can we provide the most security for JWTs?

To do this you need:

  1. Sign all available tokens with a strong key.  Note that this key should only be stored on your server and should not exist anywhere else.  At this time, when the server receives a command from the user, the validity of the message signed to the server by the server is fully measured based on the keys on it.
  2. You must use JWE or JSON Web Encryption if you have stored sensitive and specific information in the tokens. This is because JWTs only have digital signatures and are not encrypted.
  3. For added security, you only need to send tokens over the HTTPS protocol.
  4. If you use cookies to store tokens. You should only use Secure to avoid Cross-Site Scripting XSS attacks. 
  5. Consider the expiration date of the issued tokens in a principled and logical manner.

And in the end,

Mirbozorgi website does its best to help you solve their problems by providing useful articles. Email me if you have any questions.

Leave A Comment

Captcha 80 + = 90

Please Send Email

Your message sent successfully
There has been an error