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
{
"alg": "HS512", // algorithm used to encrypt the token
"typ": "JWT" // type of token
}
Payload
{
"nameid": "8", // id
"unique_name": "frank", // username
"nbf": 1511110407, // when the token becomes valid (usually same as issued at)
"exp": 1511196807, // expiration
"iat": 1511110407, // when the token was issued.
}
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
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
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.
{
"AppSettings": {
"Token": "secretpassword12345"
},
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=EFConnect;Trusted_Connection=True;Integrated Security=SSPI"
},
// ...
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 update-index --assume-unchanged appsettings.json
Git ignores this file from this point on.
To undo it if you need:
git update-index --no-assume-unchanged appsettings.json
Last updated