Files
ROLAC/API/ROLAC.API/Controllers/AuthController.cs
T
Chris Chen 2aa095c158 Task 11: Smoke test fixes (all 5 scenarios pass)
TokenService.GenerateRefreshToken():
  - Switched to URL-safe Base64 (RFC 4648 §5): +→-, /→_, no = padding.
  - Characters are unreserved per RFC 6265, so Response.Cookies.Append
    does NOT percent-encode the value.  Request.Cookies reads back exact value.

AuthController:
  - CookieOptions.Secure = !env.IsDevelopment()
    Plain HTTP in local dev works; HTTPS-only in staging/production.
  - Inject IWebHostEnvironment for environment-aware Secure flag.

TokenServiceTests:
  - Updated GenerateRefreshToken test: 86-char URL-safe Base64 instead
    of 64-byte standard Base64.  16/16 tests pass.

Smoke test results (http://localhost:5209):
  1. POST /api/auth/login       → 200 + rolac_rt cookie + JWT
  2. POST /api/auth/refresh     → 200 + new token (rotation)
  3. POST /api/auth/logout      → 204 + cookie cleared
  4. Refresh with revoked token → 401
  5. Wrong password             → 401

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-26 19:28:20 -07:00

127 lines
4.4 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ROLAC.API.DTOs.Auth;
using ROLAC.API.Services;
namespace ROLAC.API.Controllers;
[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
private const string CookieName = "rolac_rt";
private const int CookieMaxAge = 30 * 24 * 60 * 60; // 30 days in seconds
private readonly IAuthService _authService;
private readonly IWebHostEnvironment _env;
public AuthController(IAuthService authService, IWebHostEnvironment env)
{
_authService = authService;
_env = env;
}
// -------------------------------------------------------------------------
// POST /api/auth/login
// -------------------------------------------------------------------------
/// <summary>Authenticates a user and returns an access token.</summary>
[HttpPost("login")]
[AllowAnonymous]
[ProducesResponseType(typeof(LoginResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Login([FromBody] LoginRequest request)
{
try
{
var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
var device = Request.Headers.UserAgent.FirstOrDefault();
var (response, raw) = await _authService.LoginAsync(request, ip, device);
SetRefreshCookie(raw);
return Ok(response);
}
catch (UnauthorizedAccessException ex)
{
return Unauthorized(new { message = ex.Message });
}
}
// -------------------------------------------------------------------------
// POST /api/auth/refresh
// -------------------------------------------------------------------------
/// <summary>
/// Rotates the refresh token (read from the HttpOnly cookie) and returns a
/// new access token.
/// </summary>
[HttpPost("refresh")]
[AllowAnonymous]
[ProducesResponseType(typeof(LoginResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Refresh()
{
var raw = Request.Cookies[CookieName];
if (string.IsNullOrEmpty(raw))
return Unauthorized(new { message = "Refresh token not found." });
try
{
var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
var (response, newRaw) = await _authService.RefreshAsync(raw, ip);
SetRefreshCookie(newRaw);
return Ok(response);
}
catch (UnauthorizedAccessException ex)
{
ClearRefreshCookie();
return Unauthorized(new { message = ex.Message });
}
}
// -------------------------------------------------------------------------
// POST /api/auth/logout
// -------------------------------------------------------------------------
/// <summary>Revokes the current refresh token and clears the cookie.</summary>
[HttpPost("logout")]
[AllowAnonymous]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> Logout()
{
var raw = Request.Cookies[CookieName];
if (!string.IsNullOrEmpty(raw))
await _authService.LogoutAsync(raw);
ClearRefreshCookie();
return NoContent();
}
// -------------------------------------------------------------------------
// Private helpers
// -------------------------------------------------------------------------
/// <summary>
/// <c>Secure</c> is set to <c>true</c> everywhere except in the local
/// Development environment so that the cookie works over plain HTTP during
/// dev and smoke-test runs, but is always HTTPS-only in staging/production.
/// </summary>
private void SetRefreshCookie(string rawToken)
=> Response.Cookies.Append(CookieName, rawToken, new CookieOptions
{
HttpOnly = true,
Secure = !_env.IsDevelopment(),
SameSite = SameSiteMode.Strict,
MaxAge = TimeSpan.FromSeconds(CookieMaxAge),
Path = "/api/auth",
});
private void ClearRefreshCookie()
=> Response.Cookies.Delete(CookieName, new CookieOptions
{
HttpOnly = true,
Secure = !_env.IsDevelopment(),
SameSite = SameSiteMode.Strict,
Path = "/api/auth",
});
}