mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 14:20:06 +01:00
feat: jwt token example
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user