Search code examples
jwtrestful-authentication

What benefit does JWT provide?


I have implemented JWT based security in a test Core Web API REST project, it is working fine but I am not sure that I see the benefit of this. The web says JWT is good because it's lightweight and can be used to verify that the source of data but in my implementation:

  • The client first provides a username and password to authenticate
  • If user + pwd is ok the a token is returned and every subsequent call to the api uses that jwt token (instead of the username and password) to authenticate.

This is fine but why not just use the username + password on every call to the api (and skip the complication of managing the token)? In fact in my case there's additional complications because I now have to factor in an expiry date (of the token) that resides outside of my system.

Can someone explain what I'm missing here?


Solution

  • One of the main benefits and motivations for using JWT is that it allows your server side application to push all session state information outside of the application. That is, in a theoretical limit, a JWT implementation is actually stateless.

    To directly answer your question, we can compare the workflows for what happens when username/password is submitted in every request versus submitting a JWT.

    First, a JWT contains a claims section, which is typically written by the issuer of the token, i.e. the server side application. One of the fields is called exp, and contains the expiry time of the token. One property of JWT is that it is not possible for the user to tamper with them. This is enforced via a checksum, which would change if any part of the JWT changes. Taken together, this means that the user cannot alter the expiry time (or any other claim), and the server can implicitly trust this time. When the user submits a request with a JWT, in theory all the server has to do is just check exp to see if the token still be valid. That is, the session state actually lives outside the application, at least in theory.

    In contrast, when the user submits a username/password each time, the server has no way of knowing what to do just based on that information. Rather, the server has to maintain the session state itself, and this can be costly both in terms of memory and performance.

    In practice, JWT is never completely stateless, but, using a good implementation, it is usually possible to get the memory footprint very small, requiring only a bit of space in a cache (e.g. Redis or a similar tool).