How JWT Authentication works?

How JWT Authentication works?

Authentication and Authorization with JSON Web Token (JWT) in-depth

What is JWT?

JWT stands for 'JSON Web Token', So they are a stateless solution for authentication in which there is no need to store any session state on the server which is again perfect for restful APIs because restful APIs should be stateless every time.

What happens in JWT?

So here in JWT the user or client starts by making a post request with some parameters which are necessary for login or sign up like email or username and password.

example post request:

{
"email":"abdul@gmail.com",
"password":"richardHendricks"
}

So a simple post request for login looks like this.

So when a user sends these parameters then the application checks its database whether this email or username exists or not if exists then the application will check for the password and whether the password is the same or not.

If the user exists and the password is the same then the server sends that JWT back to the client which will store it either in cookies or in local storage just like this the user is authenticated and logged into our app.

Now let's see what happens when a user requests a protected data

When a user sends a request which is asking for protected data from the server. then the server will send it to the JWT and JWT will check whether the user is valid or not if it is then only the server will send back the protected data as a response. This only works when a user hits a get request.

Deep dive into how JWT works.

So a JWT is an encoded string made up of three parts. The header, The payload and the signature.

The header: the header is just the metadata of the token(here token means the secret key generated by the JWT) itself.

The payload: it is the data that we can encode into the token the more data we want to encode here the bigger the JWT.

The signature: the signature is created using the header, the payload and the secret key that is saved on the server this process is called signing the JSON web token.

This is how JWT looks like

So when you log in or sign up the header and payload with a secret key create a signature. and header+payload and signature are sent to the JWT to a client. and a client sends the JWT to the server's header+payload which creates a test signature.

Here comes the verifying process in action when a server get's the JWT from a client it contains an original signature received from the user.

now the JWT compares the test signature with the original signature.

ex:

test signature == original signature -->Data has not been modified --> Authenticated

test signature != original signature --> Data has been modified --> Not Authenticated

note:

without the secret key, no one will be able to manipulate the JWT data because they cannot create a valid signature for the new data.