api e token con ck in db

This commit is contained in:
Riccardo Usardi committed 2025-07-09 18:51:18 +02:00
1 parent a172f05269
commit 2db9525570
18 files changed
+570 -161

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace uWine.Api.Controllers
{
[ApiController]
[Route("/[controller]")]
public class TestController : Controller
{
private readonly IConfiguration _configuration;
public TestController(IConfiguration configuration) {
_configuration = configuration;
}
[HttpGet("cklogin")]
public IActionResult test()
{
try
{
var TUserId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var userId = User.FindFirst("userId").Value;
var role = User.FindFirst(ClaimTypes.Role)?.Value;
return Ok(new { userId, TUserId, role });
}
catch
{
return Unauthorized("\"title\": \"Unauthorized\"");
}
}
}
}
+72 -3
View File
@@ -1,14 +1,83 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using uWine.Core.Domain.Entities;
using uWine.Core.Infrastructure.Services;
namespace uWine.Api.Controllers
{
[ApiController]
[Route("/login/")]
[Route("/[controller]")]
public class UserController : Controller
{
public IActionResult Index()
private readonly IConfiguration _configuration;
readonly AuthenticationService _authenticationService;
public UserController(IConfiguration configuration, AuthenticationService authenticationService)
{
return View();
_configuration = configuration;
_authenticationService = authenticationService;
}
//public IActionResult Index()
//{
// return View();
//}
[HttpGet("login")]
public IActionResult LoginWithBasic()
{
if (!Request.Headers.ContainsKey("Authorization"))
return Unauthorized("Authorization header missing");
var authHeader = Request.Headers["Authorization"].ToString();
if (!authHeader.StartsWith("Basic "))
return Unauthorized("Invalid auth scheme");
var encodedCredentials = authHeader.Substring("Basic ".Length).Trim();
var decodedBytes = Convert.FromBase64String(encodedCredentials);
var decodedCredentials = Encoding.UTF8.GetString(decodedBytes);
var parts = decodedCredentials.Split(':', 2);
if (parts.Length != 2)
return Unauthorized("Invalid credentials format");
var user = new User { Username = parts[0], Password = parts[1] };
var auth = _authenticationService.IsAuthenticated(user);
// 🔐 Autenticazione fittizia (da sostituire con verifica DB)
if (!auth)
return Unauthorized("Credenziali non valide");
user = _authenticationService.User(user);
var token = GenerateJwtToken(user);
return Ok(new { access_token = token });
}
private string GenerateJwtToken(User user)
{
var jwtSettings = _configuration.GetSection("JwtSettings");
var claims = new[]
{
new Claim("userId", user.Id.ToString()),
new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Role, user.Role.Id.ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Secret"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: jwtSettings["Issuer"],
audience: jwtSettings["Audience"],
claims: claims,
expires: DateTime.UtcNow.AddMinutes(Convert.ToDouble(jwtSettings["ExpiresInMinutes"])),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}