**Introduction
JWT authentication and session authentication are ways to authenticate users of your web app.
In this article we will explain the details of JWT, its structure along with its pros and cons.
JWT stands for JSON Web Token, and it is a commonly used stateless user authentication standard used to securely transmit information between client and server in a JSON format.
A JWT is encoded and not encrypted by default.
It is digitally signed using a secret key known only to the server.
It can be encrypted, but for this article we will focus on signed non-encrypted tokens.
**
Structure of JWT
**
A JSON Web Token consists of 3 parts separated by a period.
The header, the payload, and the signature.
Each section is base64 encoded
**
Header
**
The header consists of token type, which is JWT, and the signing algorithm used, such as HMAC SHA256 or RSA.
{
"typ": "JWT",
"alg": "HS256"
}
**
Payload
**
The payload consists of the claims.
Claims are statements about the user, and additional data.
For example, we have the time the token was issued at.
We also have its expiration time, because tokens should expire.
{
"iss": "example_issuer",
"sub": "user_id123",
"exp": 1644768000,
"iat": 1644744000
}
**
Signature
**
The signature is most important part of a JWT.
It is calculated using the header, the payload, and the secret, which are fed to the signing algorithm to use.
signature = HMAC-SHA256(base64urlEncode(header) + "." + base64urlEncode(payload), secret_salt )
Steps
The steps involved in a typical JWT authorization flow are as follows:
1- Authentication: The user signs in using username and password, or using for example Google or Facebook.
The server verifies the provided credentials.
2- Token Generation & sending token to client: The server will generate the JWT and send it to the client, which stores it for future use.
3*-Sending the Token to server*: When the client wants to access a protected resource on the server, it sends the JWT in the Authorization header of the HTTP request.
axios.get(URL, {
headers: {
'Authorization': 'Bearer ' + token,
},
})
4-Verifying the Token: The server receives the request and verifies the JWT by checking its signature using the secret key that was used to sign it.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x1wtz6vfzqavwm94wkdz.png)
If the JWT is valid, the server extracts the information contained in it and uses it to determine what actions the user is authorized to perform.
5- Authorizing the Request: If the user is authorized to access the resource, the server returns the requested data. If the user is not authorized, the server returns an error message
Top comments (0)