using System.ComponentModel.DataAnnotations; using System.Security.Claims; using HealthApp.Security; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.BearerToken; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; namespace HealthApp.Controllers; [ApiController] [Route("api/authentication")] public sealed class AuthenticationController(PrototypeAccounts accounts, IOptionsMonitor options) : ControllerBase { [AllowAnonymous] [HttpPost("login")] public IActionResult Login(LoginRequest request) { var account = accounts.Verify(request.AccountId, request.Password); if (account is null) return Unauthorized(new { title = "Invalid credentials." }); var principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, account.AccountId), new Claim(ClaimTypes.Role, account.Role) }, "Bearer")); var settings = options.Get("Bearer"); var issued = settings.TimeProvider!.GetUtcNow(); var expiry = issued.Add(settings.BearerTokenExpiration); // Use the framework's ticket protector and bearer validation. No refresh endpoint/token. var ticket = new AuthenticationTicket(principal, new AuthenticationProperties { IssuedUtc = issued, ExpiresUtc = expiry }, "Bearer"); Response.Headers.CacheControl = "no-store"; Response.Headers.Pragma = "no-cache"; return Ok(new { accessToken = settings.BearerTokenProtector.Protect(ticket), tokenType = "Bearer", expiresIn = (long)settings.BearerTokenExpiration.TotalSeconds, accountId = account.AccountId, role = account.Role }); } public sealed record LoginRequest([Required] string AccountId, [Required] string Password); }