So your working on a web app and you realize you want to allow them have accounts and login and out. To accomplish this, you can use a number of different things, or just use what ever your web framework (ASP.NET MVC, Express, Rails, and etc) of choose does.
Or you can use this thing called “Token Authentication”. Now what it is, is exactly what it sounds like, its just a token you pass between your client (browser) and server to validate your request.
You might be thinking well that sounds okay but what stops someone from capturing your token and pretending to be you. Or what would stops someone from making a fake token ?
JWT (JSON Web Token) stops all those things. It is self contained and can hold a variety of different information. Its structure can be broken down into three parts:
- Header (can be decoded by anyone)
- Contains what algorithm was used to encrypt it
- Payload (can be decoded by anyone)
- The info (user name, id, expiry date and etc) stored inside the token
- Got to be careful with what type of info you put in here
- What the server uses to actually validate the token.
- Generated by doing the following :
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
- That “secret” part is what is used to generate the signature, and lives on your server.
So that is why:
- A person cannot capture your token and infinity use it , since we can specify a expiry date.
- A person cannot make a fake one, since we hash the token with a secret that only lives on the server
A few cool side features of using a JWT is that the server does not need to validate the user by interacting with the data store. Which may be a big deal if you want to have a high performance application. The other cool feature is that since you have reduced your authentication method to a JWT, it gives you a lot more flexibility in what ( maybe a mobile app ) can interact with your API.