ASP.NET Core 2.2 REST API #8.5 — What is a JWT and why your REST API needs it
Up Next: Setting up JWT support (Authentication)
Before proceeding to integrate Authentication with Json Web Tokens (henceforth: JWT), we need to understand how this technology works and what problems it is designed to solve.
Why sessions-cookies do not work
Let’s assume that we have a huge monolithic CMS and a user that wants to authenticate. The CMS keeps a session / state and issues a cookie to a user that he needs to send back upon every request.
This works, but what if we wanted to scale our CMS by replicating it? If we have a traffic manager routing and load balancing requests on multiple CMS instances, the above paradigm does not work.
The need for JWT
REST APIs are stateless by definition. Every request is self contained. It should not matter which server the request is processed on. Every request is going to have a JWT token in the header and then, any API server does not need to talk to a different service (like an authorisation server). It only needs to check (locally) the signature of the token in order to verify it’ s validity.
Let’s see how a JWT is born. The token consists of 3 parts:
- header |
JSON
- payload |
JSON
- signature |
hash
All of these get base64 encoded and separated by dots, forming the JWT.
The signature needs a 256-bit secret in order to encode the token.
After the user logs in with a username/password, the Auth Server provides a JWT that the user stores and sends back with every request.
How do the API Servers know that the token is authentic? Use the secret they share, hashing the header and the payload and then comparing this with the signature.
Encoding a payload is very different to encrypting it. You are not supposed to have sensitive data in the token, just enough to authenticate the user.
Keep in mind that this is a universal way of authentication. It does not matter how a user logs in to the system (Basic Auth, 0Auth, Google, Facebook, Apple, you name it).
Code is available on Github and the instructional videos are located on YouTube.
Keep Coding