Introduction
We are going to discuss JWT Token Authentication and Implementation using .NET Core API 6.
Before looking into this article, visit my below blog to understand the basics and details of JWT Token Authentication and Authorization and how things work using JWT.
Let’s start the implementation of the .NET Core 6 Web API.
Step 1. Create the .NET Core 6 Web API Application.
Step 2. Install the following NuGet Packages, which we are going to use throughout the application.
- Microsoft.AspNetCore.Authentication.JwtBearer
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.Design
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
- Newtonsoft.Json
- StackExchange.Redis
- Swashbuckle.AspNetCore
Step 3. Next, create a new folder, Models inside the solution, and create a Product class inside that.
namespace WebAPI.Model
{
public class Product
{
public int ProductId { get; set; }
public string? ProductName { get; set; }
public string? ProductDescription { get; set; }
public int ProductCost { get; set; }
public int ProductStock { get; set; }
}
}
Step 4. Create one DbContextClass inside the Data folder used for Database operation.
using Microsoft.EntityFrameworkCore;
using WebAPI.Model;
namespace WebAPI.Data {
public class DbContextClass: DbContext {
protected readonly IConfiguration Configuration;
public DbContextClass(IConfiguration configuration) {
Configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder options) {
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
}
public DbSet < Product > Products {
get;
set;
}
}
}
Step 5. Later on, Create ProductController inside the Controllers folder.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebAPI.Cache;
using WebAPI.Data;
using WebAPI.Model;
namespace WebAPI.Controllers {
[Route("api/[controller]")]
[ApiController, Authorize]
public class ProductController: ControllerBase {
private readonly DbContextClass _context;
private readonly ICacheService _cacheService;
public ProductController(DbContextClass context, ICacheService cacheService) {
_context = context;
_cacheService = cacheService;
}
[HttpGet]
[Route("ProductsList")]
public async Task < ActionResult < IEnumerable < Product >>> Get() {
var productCache = new List < Product > ();
productCache = _cacheService.GetData < List < Product >> ("Product");
if (productCache == null) {
var product = await _context.Products.ToListAsync();
if (product.Count > 0) {
productCache = product;
var expirationTime = DateTimeOffset.Now.AddMinutes(3.0);
_cacheService.SetData("Product", productCache, expirationTime);
}
}
return productCache;
}
[HttpGet]
[Route("ProductDetail")]
public async Task < ActionResult < Product >> Get(int id) {
var productCache = new Product();
var productCacheList = new List < Product > ();
productCacheList = _cacheService.GetData < List < Product >> ("Product");
productCache = productCacheList.Find(x => x.ProductId == id);
if (productCache == null) {
productCache = await _context.Products.FindAsync(id);
}
return productCache;
}
[HttpPost]
[Route("CreateProduct")]
public async Task < ActionResult < Product >> POST(Product product) {
_context.Products.Add(product);
await _context.SaveChangesAsync();
_cacheService.RemoveData("Product");
return CreatedAtAction(nameof(Get), new {
id = product.ProductId
}, product);
}
[HttpPost]
[Route("DeleteProduct")]
public async Task < ActionResult < IEnumerable < Product >>> Delete(int id) {
var product = await _context.Products.FindAsync(id);
if (product == null) {
return NotFound();
}
_context.Products.Remove(product);
_cacheService.RemoveData("Product");
await _context.SaveChangesAsync();
return await _context.Products.ToListAsync();
}
[HttpPost]
[Route("UpdateProduct")]
public async Task < ActionResult < IEnumerable < Product >>> Update(int id, Product product) {
if (id != product.ProductId) {
return BadRequest();
}
var productData = await _context.Products.FindAsync(id);
if (productData == null) {
return NotFound();
}
productData.ProductCost = product.ProductCost;
productData.ProductDescription = product.ProductDescription;
productData.ProductName = product.ProductName;
productData.ProductStock = product.ProductStock;
_cacheService.RemoveData("Product");
await _context.SaveChangesAsync();
return await _context.Products.ToListAsync();
}
}
}
Step 6. Now, we are going to use the Redis cache inside this application. If you understand how distributed Redis Cache works, check my following blog.
Step 7. Create the Cache folder inside the solution and create a few classes for Redis and Connection Helper. So, First, create ICacheService and CacheService for Redis Cache.
namespace WebAPI.Cache
{
public interface ICacheService
{
/// <summary>
/// Get Data using key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
T GetData<T>(string key);
/// <summary>
/// Set Data with Value and Expiration Time of Key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expirationTime"></param>
/// <returns></returns>
bool SetData<T>(string key, T value, DateTimeOffset expirationTime);
/// <summary>
/// Remove Data
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
object RemoveData(string key);
}
}
Next, Create a CacheService class for Redis Cache-related functionality.








PopPosted Jul 20, 2023, 1:02 AM
PM> add-migration “First”add-migration : The term 'add-migration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + add-migration “First” + ~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (add-migration:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
ovis ariesPosted Jul 4, 2023, 8:12 AM
This article is a little bloated, if the point was to display how to implement jwt token.
sahil gamitPosted Feb 21, 2023, 7:17 AM
Can you make a authenticate jwt in mvc core
sriram thPosted Jan 13, 2023, 3:39 PM
Asp.net core web api 6 no ConfigurationManager.AppSetting, how do you get it?
sriram thPosted Jan 13, 2023, 3:38 PM
Return ConnectionMultiplexer.Connect(ConfigurationManager.AppSetting["RedisURL"]); error
sriram thPosted Jan 13, 2023, 3:38 PM
Hi thanks for the article,
sriram thPosted Jan 13, 2023, 3:38 PM
Hi thanks for the article, I got error in return ConnectionMultiplexer.Connect(ConfigurationManager.AppSetting["RedisURL"]);
KutloPosted Nov 10, 2022, 6:40 PM
Hi, thanks for the great tutorial. Please just add the step on how to setup Redis and updating the RedisURL setting in appsettings.json. It had me stuck for a bit.
hnieefPosted Jul 14, 2022, 4:22 AM
How to enable run in offline mode
Hamid KhanPosted Jun 29, 2022, 9:25 AM
Well Explain..........Keep posting