Implements account login

This commit is contained in:
BinaryAlley committed 2024-11-11 15:19:50 +02:00
1 parent abc2777357
commit 38829d64ff
23 files changed
+826 -7

No files matched your search

@@ -1,7 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Models.Configuration;
using Lumina.Presentation.Web.Common.Utilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
#endregion
namespace Lumina.Presentation.Web.Common.DependencyInjection;
@@ -26,6 +28,12 @@ internal static class PresentationWebLayerConfiguration
.Bind(configuration.GetRequiredSection(ServerConfigurationModel.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
serviceCollection.AddOptions<EncryptionSettingsModel>()
.Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
return serviceCollection;
}
}
@@ -1,9 +1,13 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Filters;
using Lumina.Presentation.Web.Common.Security;
using Lumina.Presentation.Web.Common.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
@@ -34,7 +38,7 @@ public static class PresentationWebLayerServices
public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services)
{
services.AddControllersWithViews(options => options.Filters.Add(typeof(ApiExceptionFilter)))
.AddJsonOptions(options =>
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.MaxDepth = 256;
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
@@ -46,9 +50,9 @@ public static class PresentationWebLayerServices
.AddCookie(options =>
{
// basic path configuration
options.LoginPath = "/account/login";
options.LogoutPath = "/account/logout";
options.AccessDeniedPath = "/account/access-denied";
options.LoginPath = "/auth/login";
options.LogoutPath = "/auth/logout";
options.AccessDeniedPath = "/auth/access-denied";
// Cookie configuration
options.Cookie = new CookieBuilder
@@ -67,7 +71,7 @@ public static class PresentationWebLayerServices
// handle validation to support various deployment scenarios
options.Events = new CookieAuthenticationEvents
{
{
// handle redirects to work with different base paths
OnRedirectToLogin = context =>
{
@@ -81,6 +85,10 @@ public static class PresentationWebLayerServices
};
});
// add an authorization policy that ensures application is initialized with super admin account before allowing access
services.AddAuthorizationBuilder()
.AddPolicy("RequireInitialization", policy => policy.Requirements.Add(new InitializationRequirement()));
// add forwarded headers middleware to handle reverse proxy scenarios
services.Configure<ForwardedHeadersOptions>(options =>
{
@@ -126,6 +134,9 @@ public static class PresentationWebLayerServices
services.AddHttpContextAccessor();
services.AddScoped<ApiExceptionFilter>();
services.AddScoped<IAuthorizationHandler, InitializationHandler>();
services.AddSingleton<ICryptographyService, CryptographyService>();
services.AddSingleton<IUrlService, UrlService>();
return services;
}
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Configuration;
/// <summary>
/// Model for deserializing media settings.
/// </summary>
[DebuggerDisplay("{SECTION_NAME}")]
public class EncryptionSettingsModel
{
public const string SECTION_NAME = "EncryptionSettings";
/// <summary>
/// Gets or sets the root directory where media files are stored.
/// </summary>
public required string SecretKey { get; init; }
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the request model for user authentication.
/// </summary>
/// <param name="Username">The username used to authenticate.</param>
/// <param name="Password">The password used to authenticate.</param>
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) code used for two-factor authentication.</param>
[DebuggerDisplay("Username: {Username}")]
public record LoginRequestModel(
string? Username = null,
string? Password = null,
string? TotpCode = null
);
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the response model for a user authentication.
/// </summary>
/// <param name="Id">The Id of the logged in user.</param>
/// <param name="Username">The username of the logged in user.</param>
/// <param name="Token">The JWT authentication token, <see langword="null"/> if authentication failed or TOTP is required.</param>
/// <param name="UsesTotp">Indicates whether the user has Two-Factor Authentication enabled, or not.</param>
[DebuggerDisplay("Username: {Username}")]
public record LoginResponseModel(
Guid Id,
string? Username,
string? Token,
bool UsesTotp
);
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Models.Configuration;
using Microsoft.Extensions.Options;
using System;
using System.Security.Cryptography;
using System.Text;
#endregion
namespace Lumina.Presentation.Web.Common.Security;
/// <summary>
/// Service for cryptographic concerns.
/// </summary>
public sealed class CryptographyService : ICryptographyService, IDisposable
{
private readonly byte[] _key;
/// <summary>
/// Initializes a new instance of the <see cref="CryptographyService"/> class.
/// </summary>
/// <param name="encryptionSettingsModelOptions">Injected service for retrieving <see cref="EncryptionSettingsModel"/>.</param>
public CryptographyService(IOptions<EncryptionSettingsModel> encryptionSettingsModelOptions)
{
_key = Convert.FromBase64String(encryptionSettingsModelOptions.Value.SecretKey);
}
/// <summary>
/// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV).
/// </summary>
/// <param name="plaintext">The plaintext string to encrypt.</param>
/// <returns>A Base64-encoded string of the combined IV and encrypted ciphertext.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="plaintext"/> is <see langword="null"/> or empty.</exception>
public string Encrypt(string plaintext)
{
if (string.IsNullOrEmpty(plaintext))
throw new ArgumentException("Value cannot be null or empty", nameof(plaintext));
// generate a new, random 16-byte IV for each encryption to ensure unique ciphertexts
byte[] iv = new byte[16];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
rng.GetBytes(iv);
using Aes aes = Aes.Create();
aes.Key = _key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using ICryptoTransform encryptor = aes.CreateEncryptor();
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
byte[] ciphertext = encryptor.TransformFinalBlock(plaintextBytes, 0, plaintextBytes.Length);
// combine IV and ciphertext
byte[] combined = new byte[iv.Length + ciphertext.Length];
Buffer.BlockCopy(iv, 0, combined, 0, iv.Length);
Buffer.BlockCopy(ciphertext, 0, combined, iv.Length, ciphertext.Length);
return Convert.ToBase64String(combined);
}
/// <summary>
/// Decrypts a Base64-encoded string that contains both the IV and ciphertext.
/// </summary>
/// <param name="ciphertext">The Base64-encoded string containing both IV and ciphertext.</param>
/// <returns>The decrypted plaintext string.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="ciphertext"/> is <see langword="null"/>, empty, or invalid.</exception>
public string Decrypt(string ciphertext)
{
if (string.IsNullOrEmpty(ciphertext))
throw new ArgumentException("Value cannot be null or empty", nameof(ciphertext));
// decode the combined data (IV + ciphertext) from Base64
byte[] combined = Convert.FromBase64String(ciphertext);
if (combined.Length < 16)
throw new ArgumentException("Invalid ciphertext");
// extract IV and ciphertext
byte[] iv = new byte[16];
byte[] encryptedData = new byte[combined.Length - 16];
Buffer.BlockCopy(combined, 0, iv, 0, 16);
Buffer.BlockCopy(combined, 16, encryptedData, 0, encryptedData.Length);
using Aes aes = Aes.Create();
aes.Key = _key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using ICryptoTransform decryptor = aes.CreateDecryptor();
byte[] decrypted = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(decrypted);
}
/// <summary>
/// Clears sensitive key data when the service is disposed.
/// </summary>
public void Dispose()
{
Array.Clear(_key, 0, _key.Length);
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Presentation.Web.Common.Security;
/// <summary>
/// Interface for the service for cryptographic concerns.
/// </summary>
public interface ICryptographyService
{
/// <summary>
/// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV).
/// </summary>
/// <param name="plaintext">The plaintext string to encrypt.</param>
/// <returns>A Base64-encoded string of the combined IV and encrypted ciphertext.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="plaintext"/> is <see langword="null"/> or empty.</exception>
string Encrypt(string plaintext);
/// <summary>
/// Decrypts a Base64-encoded string that contains both the IV and ciphertext.
/// </summary>
/// <param name="ciphertext">The Base64-encoded string containing both IV and ciphertext.</param>
/// <returns>The decrypted plaintext string.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="ciphertext"/> is <see langword="null"/>, empty, or invalid.</exception>
string Decrypt(string ciphertext);
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Presentation.Web.Common.Models.Configuration;
using System;
using System.Buffers.Text;
#endregion
namespace Lumina.Presentation.Web.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the EncryptionSettings application configuration settings section.
/// </summary>
public class EncryptionSettingsModelValidator : AbstractValidator<EncryptionSettingsModel>
{
/// <summary>
/// Initializes a new instance of the <see cref="EncryptionSettingsModelValidator"/> class.
/// </summary>
public EncryptionSettingsModelValidator()
{
RuleFor(x => x.SecretKey)
.NotEmpty().WithMessage("Encryption secret key cannot be empty!")
.Must(value => Base64.IsValid(value.AsSpan())).WithMessage("Encryption secret key must be a base64 string!");
}
}
@@ -0,0 +1,170 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Filters;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Models.UsersManagement;
using Lumina.Presentation.Web.Common.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Controllers.UsersManagement;
/// <summary>
/// Controller for authentication related operations.
/// </summary>
[Authorize]
[Route("/auth/")]
public class AuthController : Controller
{
private readonly IApiHttpClient _apiHttpClient;
private readonly ICryptographyService _cryptographyService;
/// <summary>
/// Initializes a new instance of the <see cref="AuthController"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
public AuthController(IApiHttpClient apiHttpClient, ICryptographyService cryptographyService)
{
_apiHttpClient = apiHttpClient;
_cryptographyService = cryptographyService;
}
/// <summary>
/// Displays the view for registering a new account.
/// </summary>
[AllowAnonymous]
[InitializationCheck]
[HttpGet("register")]
public IActionResult Register()
{
// check if this is the initial super admin setup
string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP);
ViewData["RegistrationType"] = isPendingSuperAdminSetup == "true" ? "Admin" : "User";
return View(new RegisterRequestModel());
}
/// <summary>
/// Displays the view for logging in.
/// </summary>
/// <param name="returnUrl">The url to return to, after login (if any).</param>
[AllowAnonymous]
[InitializationCheck]
[HttpGet("login/{returnUrl?}")]
public IActionResult Login(string? returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
// if the user is already logged in, redirect them to the home page
if (User?.Identity?.IsAuthenticated == true)
return RedirectToAction("Index", "Home");
// check if the application is initialized (does contain at least the super user account); if it's not, redirect to registration view
string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP);
if (isPendingSuperAdminSetup == "true")
// TODO: should be:
// return View("~/Views/Auth/Register", new RegisterRequestDto());
// but doesn't work because of an ASP.NET bug: https://github.com/dotnet/AspNetCore.Docs/issues/25157
return RedirectToAction("Register", "Auth");
return View(new LoginRequestModel());
}
/// <summary>
/// Displays the view for recovering the password of an account.
/// </summary>
[AllowAnonymous]
[InitializationCheck]
[HttpGet("recover-password")]
public IActionResult RecoverPassword()
{
// if the user is already logged in, redirect them to the home page
if (User?.Identity?.IsAuthenticated == true)
return RedirectToAction("Index", "Home");
return View();
}
/// <summary>
/// Displays the view for registering a new account.
/// </summary>
[InitializationCheck]
[HttpGet("profile")]
public IActionResult Profile()
{
return View();
}
/// <summary>
/// Registers a new account.
/// </summary>
/// <param name="data">User credentials used for registration.</param>
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegisterRequestModel data)
{
// call different endpoints based on the view hidden field - registration for normal users, or initial application admin account setup
string endpoint = data.RegistrationType == "Admin" ? "initialization" : "auth/register";
// attempt API registration
RegisterResponseModel response = await _apiHttpClient.PostAsync<RegisterResponseModel, RegisterRequestModel>(endpoint, data);
return Json(new { success = true, data = response });
}
/// <summary>
/// Logs in an new account.
/// </summary>
/// <param name="data">User credentials used for login.</param>
/// <param name="returnUrl">The url to return to, after login (if any).</param>
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequestModel data, string? returnUrl = null)
{
try
{
// attempt API registration
LoginResponseModel response = await _apiHttpClient.PostAsync<LoginResponseModel, LoginRequestModel>("auth/login", data);
// store the received token in a secure cookie
Response.Cookies.Delete("Token");
Response.Cookies.Append("Token", _cryptographyService.Encrypt(response.Token!), new CookieOptions
{
Expires = DateTimeOffset.UtcNow.AddMonths(1),
Path = "/",
HttpOnly = true,
Secure = true
});
// tell asp.net we are logged in
List<Claim> claims =
[
new Claim(ClaimTypes.Name, response.Username!),
new Claim(ClaimTypes.NameIdentifier, response.Id.ToString()!),
new Claim("Token", response.Token!),
];
ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
// return success status and redirect URL
return Json(new { success = true, data = string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl) ? Url.Content("~/") : Url.Content(returnUrl) });
}
catch (ApiException ex)
{
// in this particular case, we DO NOT want to let the ApiExceptionFilter take care of this exception, because when the user has 2FA enabled, the first auth step involves sending
// only the username and password, in which case the server API will respond with a validation error, that TOTP code is not valid (empty); it is then that we catch this error here
// and display the form that asks the user for the TOTP code
if (ex.ProblemDetails is not null && ex.ProblemDetails.Extensions?.Count > 0 && ex.ProblemDetails.Extensions.TryGetValue("errors", out JsonElement errorsObj))
if (errorsObj is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object)
foreach (JsonProperty error in jsonElement.EnumerateObject())
if (error.Value.ValueKind == JsonValueKind.Array)
foreach (JsonElement errorValue in error.Value.EnumerateArray())
if (errorValue.ValueKind == JsonValueKind.String && errorValue.GetString() == "InvalidTotpCode" && string.IsNullOrEmpty(data.TotpCode))
return Json(new { success = true, data = new { isTotpRequired = true } }); // only get here when user did not enter a TOTP code at all, otherwise rethrow the validation error
throw;
}
}
}
@@ -0,0 +1,89 @@
@*
/auth/login/
*@
@using Lumina.Presentation.Web.Common.Models.UsersManagement
@using Lumina.Presentation.Web.Common.Services
@inject IUrlService _urlService
@model LoginRequestModel
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
<div class="shine-effect"></div>
<form asp-controller="Auth" asp-action="Login" method="post" id="login-form" class="inline">
@Html.AntiForgeryToken()
<input type="hidden" name="ReturnUrl" value="@ViewData["ReturnUrl"]" />
<div class="form-container">
<!-- Username -->
<div class="form-row">
<div class="form-label">
<label asp-for="Username">Username</label>:
</div>
<div class="form-field">
<input asp-for="Username" autocomplete="username" class="enlightenment-input" />
</div>
</div>
<!-- Password -->
<div class="form-row">
<div class="form-label">
<label asp-for="Password">Password</label>:
</div>
<div class="form-field">
<input type="password" asp-for="Password" autocomplete="current-password" class="enlightenment-input" />
</div>
</div>
<div class="form-row">
<button id="btnRecoverPassword" type="button" class="abort-button h-22px w-150px" data-link="@Url.Action("RecoverPassword", "Auth")">Recover Password</button>
<button id="btnLogin" type="submit" class="confirm-button h-22px w-100px">Login</button>
</div>
<!-- 2FA -->
<div class="form-row mt-10 hidden" id="divTotpCode">
<div class="form-label">
<label asp-for="TotpCode">Totp Code</label>
</div>
<div class="form-field">
<input type="number" asp-for="TotpCode" autocomplete="one-time-code" class="enlightenment-input" />
</div>
</div>
<div class="form-row">
<button type="submit" id="btnValidateTotp" class="confirm-button h-22px w-100px hidden">Validate Code</button>
</div>
</div>
</form>
</div>
@section Scripts {
<script type="text/javascript" defer>
document.getElementById('login-form').addEventListener('submit', async (event) => {
event.preventDefault();
const form = event.target;
const txtUsername = form.querySelector('[name="Username"]');
const txtPassword = form.querySelector('[name="Password"]');
const txtTotpCode = form.querySelector('[name="TotpCode"]');
const divTotpCode = document.getElementById('divTotpCode');
const btnLogin = document.getElementById('btnLogin');
const btnRecoverPassword = document.getElementById('btnRecoverPassword');
const btnValidateTotp = document.getElementById('btnValidateTotp');
const formData = {
Username: txtUsername.value,
Password: txtPassword.value,
TotpCode: txtTotpCode.value
};
const data = await callApiPostAsync('/auth/login', formData);
if (data && data.isTotpRequired) {
txtUsername.disabled = true;
txtPassword.disabled = true;
btnLogin.disabled = true;
btnRecoverPassword.disabled = true;
divTotpCode.classList.replace('hidden', 'inline');
btnValidateTotp.classList.replace('hidden', 'block');
txtTotpCode.focus();
}
else if (data)
window.location.href = data;
});
document.getElementById('btnRecoverPassword').addEventListener('click', () => {
window.location.href = '@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")';
});
</script>
}
@@ -1,4 +1,7 @@
{
"EncryptionSettings": {
"SecretKey": "" // base64 string
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {