2.8: Token Authentication
Introduction
In order for our users to login, we will have to provide a token to verify their identity. This is better than having application make a call to the database to check credentials everytime they make a request. When a user logs in, they are given a token. All of their subsequent requests include that token - we don't have to query the database every time they make a request.
We'll be using a Token called a JSON Web Token (JWT)
A JWT has three parts:
Header
Payload
The payload can contain lots of other information that we can provide. It's important to remember that the token can be easily decrypted - so, don't include information that should be secure.
Secret
The secret above is stored on the server - and is used to validate the token
Read more about JWT if you are interested or would like to understand more.
Adding a Token Key
To generate our JWT, we need to have a key that our server can use to validate tokens.
It could be hardcoded into the application - but, it's better to use a configuration file.
In appsettings.json
- add a new section called AppSettings
with a Token
key.
As the value to the token key - choose almost anything you'd like. The key needs to be more than 8 characters long (4 bytes) to be successfully encrypted.
In the real world, this wouldn't be secure. You can go here and generate a more secure key if you'd like.
If you want to provide more security, you can prevent Git from checking in changes to this file so that it doesn't get pushed to GitHub.
Git ignores this file from this point on.
To undo it if you need:
Last updated