Introduction To JWT(JSON Web Token)
In these article I am going to give a general overview about JWT. So,let's just start with the first question...
1) What is JSON Web Token ?
Definition given on there website : JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.
As from the above definition we can understand that JWT are used to transfer data securely as a JSON object.The most common case scenario of transferring data is between your client and server and with the help of JWT you can transfer your data securely.The JWT structure mainly consist of three parts Header,Payload and Signature. Let's see the structure of JWT below.
2) What is the JWT structure ?
The JWT structure mainly consist of three parts Head,Payload and signature separated by dots.
JWT Structure:
i) Header : It consist of algorithim used to encode JWT and type of token which is by default JWT.
ii) Payload : It generally consist of the user's data which is passed between the client and server.
iii) Signature : It is created on server side by using the header,the payload and the secret. For example if you are using node as your server and you have installed jsonwebtoken package then it provides a method sign(payload,secret key,[options, callback]) and in the options you can also provide key like expiresIn which let you specify the time for which the token will be valid.And the output of the method is a three Base64-URL strings separated by dots then which you can pass in the response to the request made by client.Let us now take a look where we can use JWT.
3) Where to use JWT ?
The most common scenario where JWT is used is for doing authorization.Let's take an example of ecommerce application, on these application you won't want the user's to access certain routes or perform action till user has been logged in and verified. So, in these case what you can do is that when the user log's in you can send the JWT token in which payload you have passed user certain info like email or id generated on server in the response to the client.Now when the user want's to access the certain private routes , now the client will sent the token in request header and on the server side you can decode that token using another method verify(token,secret,[options, callback]) with the help of which you can decode the token and get the user information and verify in your db.If the token is not valid, in the verify method callback you get the error if the token is valid you will get the decoded user information. Apart from authorization you can use JWT for transferring information securely.
I hope the article helps to give you a genral overview about JSON Web Token.