How to secure your endpoints using JWT in .NET Core ?

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

How to secure your endpoints using JWT in .NET Core

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 with Authorize on your controller

Let’s see last two steps. Suppose in our appsetting file we have some configuration for JWT

How to secure your endpoints using JWT in .NET Core

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.

How to secure your endpoints using JWT in .NET Core

Adding it in Pipeline

How to secure your endpoints using JWT in .NET Core

That is all you need to do , just add [Authorize] attribute now to your controllers.

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place