What is JWT ?
JSON Web Token are extensively used in authentication and authorization they make sure that this user is . JWT has three parts :
- Header
- Payload
- Signature
Header contains details about encryption algorithm ,payload contains key-value based data which we call claims mostly and third part is signature which combines header and payload in Base64 along with secret key and hashes it.
How JWT Works ?
User sends email & password and gets authenticated and at the same time we generated a string which we call token. So for every next request that comes to our endpoints that string is attached in header of request and we use it to verify identity of user.
Let’s not dig more in JWT and focus on its implementation.
Enable it in .NET 6.0 ?
It has pretty simple three steps.
- Install
Microsoft.AspNetCore.Authentication.JWTBearer
Nuget Package - Configure your
Program.cs
- Remove
AllowAnonymous
attribute and change it withAuthorize
on your controller
Let’s see last two steps. Suppose in our appsetting file we have some configuration for JWT
NOTE : Unfortunately it is not practiced a lot but best ways of keeping this secret is on some secure Vaults , it is not best to keep it here in appsetting
I have added local hosts but you can add the valid issuer URL and the audience for which it is intended.
Adding it in Pipeline
That is all you need to do , just add [Authorize]
attribute now to your controllers.
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place