I could not see the code which enables JWT authentication and issues JWT in your question above. Shown below is a sample which I use in my ASP.NET Core Web API project. Hope they can help:
(1) Install NuGet package Microsoft.AspNetCore.Authentication.JwtBearer.
(2) Register JWT authentication schema in the Program.cs:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using WebApi.Data;
using Microsoft.EntityFrameworkCore;
namespace WebApi
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add the following for JWT authentication
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"]!))
};
});
// code omitted
// Add the following for JWT authentication
app.UseAuthentication();
// code omitted
(3) Add key and issuer in appsettings.json
{
... code omitted ...
"AllowedHosts": "*",
"Jwt": {
"Key": "veryVerySecretKeyWhichMustBeLongerThan32",
"Issuer": "https://<your hostname>"
}
}
(4) Add controller and action method to issue JWT token
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
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;
private readonly UserManager<IdentityUser> _userManager;
public TokenController(IConfiguration config,
UserManager<IdentityUser> userManager)
{
_config = config;
_userManager = userManager;
}
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> CreateToken(LoginModel login)
{
string? id = login.Username;
string? pw = login.Password;
IActionResult response = Unauthorized();
if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(pw))
{
var user = await _userManager.FindByNameAsync(id);
if (user != null &&
await _userManager.CheckPasswordAsync(user, pw))
{
var tokenString = BuildToken();
response = Ok(new { token = tokenString });
}
}
return response;
}
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; }
}
}