using Books.Api.Authentication; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Books.Api.Controllers; [Route("api")] [ApiController] public class AuthController : ControllerBase { [HttpGet("login")] [Authorize] public IActionResult Login([FromQuery] string? returnUrl) { // The [Authorize] attribute triggers the OIDC challenge if not authenticated. // If we reach here, the user is authenticated - redirect back to the app. // Validate returnUrl to prevent open redirect attacks if (returnUrl != null && !Url.IsLocalUrl(returnUrl)) returnUrl = "/"; return Redirect(returnUrl ?? "/"); } [HttpGet("logout")] public async Task Logout() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Ok(new { message = "Logged out successfully" }); } [HttpGet("profile")] [Authorize] public IActionResult Profile() { var userContext = User.GetUserContext(); if (userContext == null) { return Unauthorized(); } return Ok(userContext); } }