Please try the followings:
(1) Create Web API project with Authentication type: None.
(2) Install NuGet package Microsoft.AspNetCore.Authentication.JwtBearer.
(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; }
}
}
}