210 lines
8.0 KiB
C#
210 lines
8.0 KiB
C#
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.WebUtilities;
|
|
using UniVerse.Application.DTOs.Auth;
|
|
using UniVerse.Application.Interfaces;
|
|
using System.Security.Cryptography;
|
|
using System.Security.Claims;
|
|
|
|
namespace UniVerse.Api.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/v1/auth")]
|
|
public class AuthController : ControllerBase
|
|
{
|
|
private readonly IAuthService _auth;
|
|
private readonly IConfiguration _config;
|
|
|
|
private const string MicrosoftStateCookieName = "msAuthState";
|
|
private const string MicrosoftReturnUrlCookieName = "msAuthReturnUrl";
|
|
|
|
public AuthController(IAuthService auth, IConfiguration config)
|
|
{
|
|
_auth = auth;
|
|
_config = config;
|
|
}
|
|
|
|
[HttpPost("login/microsoft")]
|
|
public async Task<ActionResult<AuthResponse>> LoginMicrosoft([FromBody] LoginMicrosoftRequest request)
|
|
{
|
|
var result = await _auth.LoginWithMicrosoftAsync(request.AuthorizationCode, request.RedirectUri);
|
|
SetRefreshTokenCookie(result.RefreshToken);
|
|
return Ok(result.Response);
|
|
}
|
|
|
|
// Server-driven auth flow: frontend just navigates here; backend builds Microsoft authorize URL.
|
|
// Optional returnUrl is stored in a short-lived cookie and used by callback.
|
|
[HttpGet("login/microsoft")]
|
|
[AllowAnonymous]
|
|
public IActionResult LoginMicrosoftRedirect([FromQuery] string? returnUrl = null)
|
|
{
|
|
var tenantId = _config["AzureAd:TenantId"];
|
|
var clientId = _config["AzureAd:ClientId"];
|
|
var instance = _config["AzureAd:Instance"] ?? "https://login.microsoftonline.com/";
|
|
|
|
if (string.IsNullOrWhiteSpace(tenantId) || string.IsNullOrWhiteSpace(clientId))
|
|
return Problem("Microsoft authentication is not configured (AzureAd:TenantId/ClientId).", statusCode: StatusCodes.Status500InternalServerError);
|
|
|
|
var redirectUri = _config["AzureAd:RedirectUri"] ?? BuildAbsoluteUrl("/api/v1/auth/callback/microsoft");
|
|
|
|
var state = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
|
|
Response.Cookies.Append(MicrosoftStateCookieName, state, new CookieOptions
|
|
{
|
|
HttpOnly = true,
|
|
Secure = Request.IsHttps,
|
|
SameSite = SameSiteMode.Lax,
|
|
Expires = DateTimeOffset.UtcNow.AddMinutes(10)
|
|
});
|
|
|
|
if (!string.IsNullOrWhiteSpace(returnUrl) && IsAllowedReturnUrl(returnUrl))
|
|
{
|
|
Response.Cookies.Append(MicrosoftReturnUrlCookieName, returnUrl, new CookieOptions
|
|
{
|
|
HttpOnly = true,
|
|
Secure = Request.IsHttps,
|
|
SameSite = SameSiteMode.Lax,
|
|
Expires = DateTimeOffset.UtcNow.AddMinutes(10)
|
|
});
|
|
}
|
|
|
|
var authorizeEndpoint = $"{instance.TrimEnd('/')}/{tenantId}/oauth2/v2.0/authorize";
|
|
var scope = _config["AzureAd:Scopes"] ?? "openid profile email offline_access User.Read";
|
|
|
|
var authorizeUrl = QueryHelpers.AddQueryString(authorizeEndpoint, new Dictionary<string, string?>
|
|
{
|
|
["client_id"] = clientId,
|
|
["response_type"] = "code",
|
|
["redirect_uri"] = redirectUri,
|
|
["response_mode"] = "query",
|
|
["scope"] = scope,
|
|
["state"] = state
|
|
});
|
|
|
|
return Redirect(authorizeUrl);
|
|
}
|
|
|
|
[HttpGet("callback/microsoft")]
|
|
[AllowAnonymous]
|
|
public async Task<IActionResult> CallbackMicrosoft(
|
|
[FromQuery] string? code = null,
|
|
[FromQuery] string? state = null,
|
|
[FromQuery] string? error = null,
|
|
[FromQuery(Name = "error_description")] string? errorDescription = null)
|
|
{
|
|
if (!string.IsNullOrEmpty(error))
|
|
{
|
|
return Unauthorized(new
|
|
{
|
|
error,
|
|
errorDescription
|
|
});
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(code))
|
|
return BadRequest(new { error = "missing_code" });
|
|
|
|
var expectedState = Request.Cookies[MicrosoftStateCookieName];
|
|
if (string.IsNullOrWhiteSpace(expectedState) || string.IsNullOrWhiteSpace(state) || !string.Equals(expectedState, state, StringComparison.Ordinal))
|
|
return Unauthorized(new { error = "invalid_state" });
|
|
|
|
Response.Cookies.Delete(MicrosoftStateCookieName);
|
|
|
|
var redirectUri = _config["AzureAd:RedirectUri"] ?? BuildAbsoluteUrl("/api/v1/auth/callback/microsoft");
|
|
|
|
var result = await _auth.LoginWithMicrosoftAsync(code, redirectUri);
|
|
SetRefreshTokenCookie(result.RefreshToken);
|
|
|
|
var returnUrl = Request.Cookies[MicrosoftReturnUrlCookieName] ?? _config["AzureAd:PostLoginRedirectUri"];
|
|
Response.Cookies.Delete(MicrosoftReturnUrlCookieName);
|
|
|
|
if (!string.IsNullOrWhiteSpace(returnUrl) && IsAllowedReturnUrl(returnUrl))
|
|
{
|
|
// Put access token in URL fragment so it is not sent as Referer to the backend.
|
|
// Frontend can read it from location.hash on the landing page.
|
|
var fragment = $"access_token={Uri.EscapeDataString(result.Response.AccessToken)}&expires_at={Uri.EscapeDataString(result.Response.ExpiresAt.ToString("O"))}";
|
|
return Redirect($"{returnUrl}#{fragment}");
|
|
}
|
|
|
|
// Useful for manual testing without frontend: you'll see JSON in the browser.
|
|
return Ok(result.Response);
|
|
}
|
|
|
|
[HttpPost("login/dev")]
|
|
public async Task<ActionResult<AuthResponse>> DevLogin([FromBody] DevLoginRequest request)
|
|
{
|
|
if (!HttpContext.RequestServices.GetRequiredService<IWebHostEnvironment>().IsDevelopment())
|
|
return NotFound();
|
|
var result = await _auth.DevLoginAsync(request.Email, request.DisplayName, request.Role);
|
|
SetRefreshTokenCookie(result.RefreshToken);
|
|
return Ok(result.Response);
|
|
}
|
|
|
|
[HttpPost("refresh")]
|
|
public async Task<ActionResult<AuthResponse>> Refresh()
|
|
{
|
|
var refreshToken = Request.Cookies["refreshToken"];
|
|
if (string.IsNullOrEmpty(refreshToken)) return Unauthorized();
|
|
var result = await _auth.RefreshTokenAsync(refreshToken);
|
|
SetRefreshTokenCookie(result.RefreshToken);
|
|
return Ok(result.Response);
|
|
}
|
|
|
|
[Authorize]
|
|
[HttpPost("logout")]
|
|
public async Task<IActionResult> Logout()
|
|
{
|
|
var refreshToken = Request.Cookies["refreshToken"];
|
|
if (!string.IsNullOrEmpty(refreshToken))
|
|
await _auth.RevokeRefreshTokenAsync(refreshToken);
|
|
Response.Cookies.Delete("refreshToken");
|
|
return NoContent();
|
|
}
|
|
|
|
[Authorize]
|
|
[HttpGet("me")]
|
|
public async Task<ActionResult> Me()
|
|
{
|
|
var userId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)
|
|
?? User.FindFirstValue("sub") ?? "0");
|
|
var user = await _auth.GetCurrentUserAsync(userId);
|
|
return Ok(user);
|
|
}
|
|
|
|
private void SetRefreshTokenCookie(string token)
|
|
{
|
|
Response.Cookies.Append("refreshToken", token, new CookieOptions
|
|
{
|
|
HttpOnly = true, Secure = true, SameSite = SameSiteMode.Strict,
|
|
Expires = DateTime.UtcNow.AddDays(30)
|
|
});
|
|
}
|
|
|
|
private string BuildAbsoluteUrl(string path)
|
|
{
|
|
if (!path.StartsWith('/')) path = "/" + path;
|
|
return $"{Request.Scheme}://{Request.Host}{path}";
|
|
}
|
|
|
|
private bool IsAllowedReturnUrl(string returnUrl)
|
|
{
|
|
if (Uri.TryCreate(returnUrl, UriKind.Relative, out _))
|
|
return true;
|
|
|
|
if (!Uri.TryCreate(returnUrl, UriKind.Absolute, out var absolute))
|
|
return false;
|
|
|
|
var allowedOrigins = _config.GetSection("Cors:Origins").Get<string[]>() ?? Array.Empty<string>();
|
|
foreach (var origin in allowedOrigins)
|
|
{
|
|
if (!Uri.TryCreate(origin, UriKind.Absolute, out var allowed))
|
|
continue;
|
|
if (string.Equals(allowed.Scheme, absolute.Scheme, StringComparison.OrdinalIgnoreCase)
|
|
&& string.Equals(allowed.Host, absolute.Host, StringComparison.OrdinalIgnoreCase)
|
|
&& allowed.Port == absolute.Port)
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|