feat: jwt token example

This commit is contained in:
2025-07-15 10:22:53 +02:00
parent c277b190e6
commit b6dc1ce2cd
5 changed files with 103 additions and 1 deletions

View File

@@ -1,21 +1,32 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using QuotifyBE.Controllers;
using QuotifyBE.DTOs;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace QuotifyBE.Controllers
{
[ApiController]
[Route("[controller]")]
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;
private readonly IConfiguration _appsettings;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration appsettings)
{
_logger = logger;
_appsettings = appsettings;
}
[HttpGet(Name = "GetWeatherForecast")]
@@ -29,5 +40,48 @@ namespace QuotifyBE.Controllers
})
.ToArray();
}
[HttpPost("login")]
public IActionResult Login([FromBody] UserLoginDTO user)
{
if (user.Email == "admin" && user.Password == "password")
{
var token = GenerateJwtToken(user.Email);
return Ok(new { token });
}
return Unauthorized();
}
[HttpGet("some_values")]
[Authorize]
public IActionResult GetValues()
{
return Ok(new string[] { "value1", "value2" });
}
private string GenerateJwtToken(string username)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_appsettings["JwtSecret"]!)
// won't be null here - otherwise Program.cs wouldn't start
);
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _appsettings["DomainName"]!,
audience: _appsettings["DomainName"]!,
claims: claims,
expires: DateTime.Now.AddDays(7),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}