Jason Web Token (JWT)

What is a JWT?



It stands for JSON Web Token and it replaces the older cookie authentication and is now becoming the authentication standard.

  • Simpler & light weight.
  • Don’t have cookie authentication problems like setting Session states either in memory or database.
  • No database lookup to identify who the user is, as userId is embedded in the payload which is part of JWT’s.
  • No CORS issues as cookies are not being used.
  • Works with small and medium handheld devices (phones and iPads/tablets).

JasonWebToken


Life of a JWT

Every JWT has three parts. It begins with a header, in between is the payload, and at the end is the signature.

It all begins with the client trying to log in, where the HTTP request is send over with email and password to the backend, whether it’s for a login or just register. The backend will then validate the email and password and then 
it will encode the user ID and a few other things against the secret and something called a payload. Then our JWT, which is comprised of the header,
 payload, and signature, will be sent to the client. At this point, the client gets the JWT. It has no idea what’s inside. It doesn’t know what it is 
because it can’t decode it, only the server can, and so it just saves it inside its local storage and as long as it has that entry inside the local
 storage, it believes that it’s authenticated. Now let’s say the client restarts. The JWT is still in local storage because it’s persistent and because
 of that they’re still authenticated. No matter how many times the browser or client might restart, they’ll still be authenticated, unless,
 of course, the JWT expires.

JWT Payload Details:

JWTPayload


What if a client wants to request a restricted resource?



A restricted resource can only be accessed if you are authenticated. So to make that work, what we do is, 
we take our JWT from our local storage (on the front end web app) and embed it into an authentication header, which then gets passed back with any sort of request 
we make to our backend for our resource. That way our backend knows who we are from the payload since our user ID is in it and can authorize
us to have access to this resource.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s