I'm trying to integrate JWT tokens with a .NET 6 Web project. I've done so far. But what exactly do I need to do to make it work properly. I would appreciate it if you could move me through the code. Because I looked at the examples on the internet.
TokenRepository
public string BuildToken(string key, string issuer, Users users)
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, users.CustomerCode),
new Claim(ClaimTypes.GivenName, users.CustomerCode),
new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())
};
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var tokenDescriptor = new JwtSecurityToken(issuer, issuer, claims,
expires: DateTime.Now.AddMinutes(EXPIRY_DURATION_MINUTES), signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
}
public bool ValidateToken(string key, string issuer, string audience, string token)
{
var mySecret = Encoding.UTF8.GetBytes(key);
var mySecurityKey = new SymmetricSecurityKey(mySecret);
var tokenHandler = new JwtSecurityTokenHandler();
try
{
tokenHandler.ValidateToken(token,
new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = issuer,
ValidAudience = issuer,
IssuerSigningKey = mySecurityKey,
}, out SecurityToken validatedToken);
}
catch
{
return false;
}
return true;
}
HomeController
private readonly ILogger<HomeController> _logger;
private readonly ITokenRepository _tokenRepository;
private readonly IConfiguration _configuration;
public HomeController(ILogger<HomeController> logger, ITokenRepository tokenRepository, IConfiguration configuration)
{
_logger = logger;
_tokenRepository = tokenRepository;
_configuration = configuration;
}
public IActionResult Index()
{
Users users = new Users();
users.Email = "deneme@gmail.com";
users.CustomerCode = "123456";
string token = _tokenRepository.BuildToken(_configuration["Jwt:SigningKey"].ToString(), _configuration["Jwt:Issuer"].ToString(), users);
if (token != null)
{
HttpContext.Request.Headers.Add("token", token);
return RedirectToAction("Privacy");
}
return View();
}
[Authorize]
public IActionResult Privacy()
{
return View();
}
Program.cs
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:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SigningKey"]))
};
});
app.Use(async (context, next) =>
{
string token = context.Request.Headers["token"];
context.Request.Headers.Authorization = $"Bearer {token}";
await next();
if (context.Response.StatusCode == (int)System.Net.HttpStatusCode.Unauthorized)
{
await context.Response.WriteAsync("Token Validation Has Failed. Request Access Denied");
}
});