how to implement JWT token using .net core 8 web api

coder rock 436 Reputation points
2025-04-13T09:28:07.3866667+00:00

I am new to jwt token generation and as well as .NET core 8 web Api, so now i am building nurse recruitment portal backend implementation from scratch so below I have written code for jwt token generation and i want to check its correct way of implement from scratch. Can you suggest for build backend application according industry standards

appsetting.json

User's image

I have created Data folder name and inside created dbcontext file like this Data/ApplicationDbContext.cs

User's image

User's imageBelow is my jwt token generation code if user is exist then returning token of this location Controller/Usercontroller.cs

using coreapidotnet8.Models;

using coreapidotnet8.Services.Users;

using Microsoft.AspNetCore.Mvc;

using Microsoft.IdentityModel.Tokens;

using System.IdentityModel.Tokens.Jwt;

using System.Security.Claims;

using System.Text;

namespace coreapidotnet8.Controllers

{

[ApiController]

[Route("[controller]")]

public class UserController : ControllerBase

{

    private readonly IUserRepository _userRepository;

    public UserController(IUserRepository userRepository)

    {

        _userRepository = userRepository;

    }

    [HttpGet("GetallLoginDetails")]

    public async Task<ActionResult<List<LoginDetails>>> GetallLoginDetails()

    {

        //return await _context.LoginDetails.ToListAsync();

        var logins = await _userRepository.GetAllLoginDetailsAsync();

        return Ok(logins);

    }

    [HttpGet("GetLoginDetailsById")]

    public async Task<ActionResult<LoginDetails>> GetLoginDetailsById(string? Username, string? Password)

    {

        //return await _context.LoginDetails.ToListAsync();  GetLoginDetailsById

        var logins = await _userRepository.GetLoginDetailsById(Username, Password);

        if (logins == null || logins.Count == 0)

            return BadRequest("User is not valid");

            var token = GenerateJwtToken();

        return Ok(token);

    }



    private string GenerateJwtToken()

    {

        var tokenHandler = new JwtSecurityTokenHandler();

        var key = Encoding.ASCII.GetBytes("xxxxxxxassaaaaaaasdddxxxxxxxxxxxxxxxx");

        var tokenDescriptor = new SecurityTokenDescriptor

        {

            Subject = new ClaimsIdentity(new[] { new Claim("id", "testuser"), new Claim(ClaimTypes.Role, "Admin") }),

            Issuer = "https://localhost:7054",

            Audience = "https://localhost:7054",

            Expires = DateTime.UtcNow.AddDays(7),

            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)

        };

        var token = tokenHandler.CreateToken(tokenDescriptor);

        return tokenHandler.WriteToken(token);

    }

    [HttpPost("authenticate")]

    public async Task<IActionResult> Authenticate()

    {

        //Here you could pass user to generatejwttoeknmethod to generate the token based on the user

        var token = GenerateJwtToken();

        if (token == null)

            return BadRequest(new { message = "Username or password is incorrect" });

        return Ok(token);

    }

    public async Task<IActionResult> Register()

    {

        return Ok();

    }

}

}

ASP.NET Core Training
ASP.NET Core Training
ASP.NET Core: A set of technologies in the .NET Framework for building web applications and XML web services.Training: Instruction to develop new skills.
62 questions
{count} votes

Accepted answer
  1. SurferOnWww 4,391 Reputation points
    2025-04-14T03:53:20.1066667+00:00

    Please try the followings:

    (1) Create Web API project with Authentication type: None.

    enter image description here

    (2) Install NuGet package Microsoft.AspNetCore.Authentication.JwtBearer.

    enter image description here

    (3) Register JWT authentication scheme in Program.cs.

    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.IdentityModel.Tokens;
    using System.Text;
    
    namespace WebApi
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                var builder = WebApplication.CreateBuilder(args);
    
                // Register JWT authentication scheme
                builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddJwtBearer(options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuer = true,
                            ValidateAudience = true,
                            ValidateLifetime = true,
                            ValidateIssuerSigningKey = true,
                            ValidIssuer = builder.Configuration["Jwt:Issuer"],
                            ValidAudience = builder.Configuration["Jwt:Issuer"],
                            IssuerSigningKey = new SymmetricSecurityKey(
                                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
                        };
                    });
    
                // other code (omitted)
            }
        }
    }
    

    (4) Add Key and Issuer to appsettings.json

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "Jwt": {
        "Key": "veryVerySecretKeyWhichMustBeLongerThan32",
        "Issuer": "https://localhost:44362"
      }
    }
    

    (5) Add API which verifies username and password sent from user and returns JWT.

    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.IdentityModel.Tokens;
    using System.IdentityModel.Tokens.Jwt;
    using System.Text;
    
    namespace WebApi.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class TokenController : ControllerBase
        {
            private readonly IConfiguration _config;
    
            public TokenController(IConfiguration config)
            {
                _config = config;
            }
    
            [AllowAnonymous]
            [HttpPost]
            public IActionResult CreateToken([FromBody] LoginModel login)
            {
                string? id = login.Username;
                string? pw = login.Password;
                IActionResult response = Unauthorized();
    
                if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(pw))
                {
                    if (VerifyUser(id, pw))
                    {
                        var tokenString = BuildToken();
                        response = Ok(new { token = tokenString });
                    }
                }
    
                return response;
            }
    
            private bool VerifyUser(string id, string pw)
            {
                // verify id and password sent from user (code omitted)            
                // simply return true in this sample
                return true;
            }
    
            private string BuildToken()
            {
                var key = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes(_config["Jwt:Key"]!));
    
                var creds = new SigningCredentials(
                    key, SecurityAlgorithms.HmacSha256);
    
                var token = new JwtSecurityToken(
                    issuer: _config["Jwt:Issuer"],
                    audience: _config["Jwt:Issuer"],
                    claims: null,
                    notBefore: null,
                    expires: DateTime.Now.AddMinutes(30),
                    signingCredentials: creds);
    
                return new JwtSecurityTokenHandler().WriteToken(token);
            }
    
            public class LoginModel
            {
                public string? Username { get; set; }
                public string? Password { get; set; }
            }
        }
    }
    

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 75,051 Reputation points
    2025-04-14T17:12:39.4266667+00:00

    other than key management (keys in source code is high risk), your code is valid if the JWT issuer and validator are the same site. if at some point two sites are involved (say single sign on), then you have a security risk with using symmetric key for the JWT. you should switch to asymmetric keys.

    the most difficult part is securing the signing keys. you probably need some secrets store.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.