On the topic of authentication, most people would just assume some username/password combination or one of their social accounts(Google, FB, Twitter, etc.). This is a fair assumption, but for anyone related to application engineering, it is a way more complex setup. Honing onto the core of how authentication works, we need to ask one question. How can an application UI communicate with APIs, while validating it’s an actual user making the request. JWT!

What Is JWT

In definition, JWT stands for JSON Web Token. It is an encrypted string representation of a JSON object, typically based on some user data, that is sent to a client application to be used to authenticate communication.

To handle encryption a private key is used. This is a string that can be viewed as a “secret phrase” that should never be shared, or publicly visible. Typically this is kept in an ENV variable on the server or some form of a secure file there as well.

A good example of implementation would be something similar to the sample shown below:

    { test: 'hello' }, 
    'hi, this is a private key(secret phrase)'

What Does The Flow Look Like

Now that we know the basics of what a JWT token is, let’s transition ahead a bit into the how of it. For simplicity’s sake, let’s focus on the username/password pair. So as a user you authenticate with said pair, that data is sent to a backend API where it validates it in the system and generates a JWT. The token can be expected to reside in the response body of your request, and the client decides the best way to store it.

Once the token is received and stored by the client requesting authentication, this is where the fun begins. Because now that is the user’s key to accessing the locked API routes that require proof of a valid session. So all your API requests from the client will have to possess this key in the headers of the request. Here’s what it looks like.

'Authorization': `Bearer ${JWT Token}`

Let’s summarize all this:

  • User logs in with a username/password pair
  • The backend API confirms this pair is valid, and generates a JWT
  • This JWT is returned in the response and the requesting client stores it appropriately
  • Then, all communication to the API will have said JWT inside the Authorization header

In Closing

While authentication is complex, once you understand it, things start to slow down a lot and make more sense. This applies to the implementation flow, as well as the technical mechanics around it as well. Of course, there is always going to be more to it as you get deeper into the concepts, but for now, this base level understanding will get you where you need to in the beginning.