books/backend/Books.Api/Controllers/AuthController.cs

42 lines
1.1 KiB
C#
Raw Normal View History

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.
return Redirect(returnUrl ?? "/");
}
[HttpGet("logout")]
public async Task<IActionResult> 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);
}
}