Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. How to implement JWT Token in Asp.Net core 7

How to implement JWT Token in Asp.Net core 7

Date- Aug 01,2023 Updated Jan 2026 7359 Free Download Pay & Download
jwt authentication validate jwt token


JWT

JSON Web Token (JWT) is an open standard that defines a compact way for securely transmitting information between parties as a JSON object. It is often used in web applications to securely keep user-related data or claims which can be verified easily,

So in this we will use two different projects from same solution . One will be the web app and the second will be the web apiHow to implement JWT Token in AspNet core 7

So first of all we have to install the Nuget package in the .net core 7.0 web application which is shown in the image below:-

How to implement JWT Token in AspNet core 7 2


Now on the Home controller or the controller where you want to login and get a token you have to write following code. In the Index action  here we are passing the login credentials to the .net core 7 web api and the api will return back the jwt token for valid authentication 

    using JWTCore7.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Text.Json.Serialization;
using System.Net.Http.Headers; 
namespace JWTCore7.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IHttpClientFactory _httpClientFactory;

        public HomeController(ILogger<HomeController> logger, IHttpClientFactory httpClientFactory)
        {
            _logger = logger;
            _httpClientFactory = httpClientFactory;
        }

        public async Task<IActionResult> Index()
        {
            var httpClient = _httpClientFactory.CreateClient();

            // Set the base address of the API
            httpClient.BaseAddress = new Uri("https://localhost:7012/");

            try
            {
                // Make the API call
                var parameters = new Dictionary<string, string>
                {
                    { "username", "Admin" },
                    { "password", "123" }
                };

                // Add the parameters to the request URL as query string
                var requestUrl = QueryHelpers.AddQueryString("/WeatherForecast/Login/login", parameters);

                // Make the API call with the updated URL
                var response = await httpClient.GetAsync(requestUrl);


                // Check if the request was successful
                //response.EnsureSuccessStatusCode();

                // Read the response content as a string
                var content = await response.Content.ReadAsStringAsync();
                var token = JsonConvert.DeserializeObject<JWTAuth>(content);
                // Return the API response
               
                // Create the cookie options
                var cookieOptions = new CookieOptions
                {
                    // Set other properties as needed
                    Expires = DateTime.Now.AddDays(1),
                    HttpOnly = true,
                    Secure = true, // Set to true if your site uses HTTPS
                    SameSite = SameSiteMode.Strict // Adjust this based on your requirements
                };

                // Set the cookie with the string data
                HttpContext.Response.Cookies.Append("token", token.token, cookieOptions);

            }
            catch (HttpRequestException ex)
            {
                // Handle API call errors
                Console.WriteLine($"API call failed: {ex.Message}");
                return null;
            }
            return View();
        }

        

      
    }
}

Now in the .net core 7 api project we will add following code which will verify login details and then return back the jwt token

  using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Text;

namespace ApiCore7.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;
        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }
        private string GenerateJwtToken(string username)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.UTF8.GetBytes("C1CF4B7DC4C4175B6618DE4F55CA4"); // Replace with your secret key
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                new Claim(ClaimTypes.Name, username)
            }),
                Expires = DateTime.UtcNow.AddHours(1), // Token expiration time
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
       
        [HttpGet("login")]
        public IActionResult Login(string username,string password)
        {
            // Your login logic here...
            // After successful authentication, generate the JWT token
            // Replace with the authenticated user's username
            if (username == "Admin" && password == "123")
            {
                var token = GenerateJwtToken(username);

                // Return the token in the response
                return Ok(new { Token = token });
            }
            else
            {
                return Ok(new { Token = "" });
            }
        }
        [HttpGet(Name = "GetWeatherForecast")]
        [Authorize]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}


After getting the token in the Index method we are setting that in the cookie and then we will send that in the next api call which will require the jwt token . You can get the code of how to send jwt token  below 

  public async Task<IActionResult> GetAuthorizedData()
        {
            var httpClient = _httpClientFactory.CreateClient();
            var jwtToken = "";
            HttpContext.Request.Cookies.TryGetValue("token", out  jwtToken);
       
            // Set the base address of the API
            httpClient.BaseAddress = new Uri("https://localhost:7012/");

            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {jwtToken}");

            try
            {
                
                // Make the API call with the updated URL
                var response = await httpClient.GetAsync("/WeatherForecast/Get");


                // Check if the request was successful
                //response.EnsureSuccessStatusCode();

                // Read the response content as a string
                var content = await response.Content.ReadAsStringAsync();
                

            }
            catch (HttpRequestException ex)
            {
                // Handle API call errors
                Console.WriteLine($"API call failed: {ex.Message}");
                return null;
            }
            return View("Index");
        }

In this we are sending the jwt token and on the api controller you will see we have used the Authorize attribute to authorize the token.

Add following in Web api program.cs file

You also have to add following in the program.cs file of our .net core 7 api project.

How to implement JWT Token in AspNet core 7 3


using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "Code2night", // Replace with your issuer
            ValidAudience = "Public", // Replace with your audience
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("C1CF4B7DC4C4175B6618DE4F55CA4"))  // Replace with your secret key
    };
});

Now run the application and you will see when login api called, it will return back the jwt tokenHow to implement JWT Token in AspNet core 7 4


Now we will set this in the next apiHow to implement JWT Token in AspNet core 7 5

How to implement JWT Token in AspNet core 7 6

How to implement JWT Token in AspNet core 7 7

How to implement JWT Token in AspNet core 7 8

On the web api side we have used Authorize attribute to authorize the token. So you can see the api is being authroized and then the data is returned. You can copy the JWTAuth class from here in put it in the web application where you are calling the web api

namespace JWTCore7.Models
{
    public class JWTAuth
    {
        public string token { get; set; }
    }
}
And copy following view code

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

<a href='/Home/GetAuthorizedData'> Call Api with JWT</a>

So , now just run the application and test . You can modify the code and make it more dynamic as per your requirements. So this is how we can create and verify jwt token in asp.net core 7 application and web api. This is how to implement jwt token in Asp.Net core 7.0 .

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

How to implement JWT Token Authentication and Validate JWT Token in ASP.NET MVC using JWT
Oct 12, 2022
Implement JWT Token Authentication with Validate and Refresh Token in asp.net mvc
Mar 05, 2024
Securing DB2 Connections in ASP.NET Core Applications: Best Practices and Techniques
Apr 08, 2026
Mastering Authentication with JWT in Node.js: A Comprehensive Guide
Mar 30, 2026
Previous in ASP.NET Core
Integrate Stripe Payment Gateway In ASP.NET Core 7.0
Next in ASP.NET Core
How to use api with proxy url in Asp.Net for CORS
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,938 views
  • 2
    Error-An error occurred while processing your request in .… 11,272 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 235 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,459 views
  • 5
    Mastering JavaScript Error Handling with Try, Catch, and F… 161 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,497 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,232 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26066 views
  • Exception Handling Asp.Net Core 20797 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20288 views
  • How to implement Paypal in Asp.Net Core 19678 views
  • Task Scheduler in Asp.Net core 17578 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor