Implements authentication system

This commit is contained in:
BinaryAlley committed 2024-11-11 22:57:33 +02:00
1 parent 38829d64ff
commit a6dcf65d1c
103 files changed
+2983 -454

No files matched your search

@@ -1,7 +1,11 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Infrastructure.Core.Authentication;
using Lumina.Infrastructure.Core.Security;
using Lumina.Infrastructure.Core.Time;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
#endregion
@@ -25,6 +29,12 @@ public static class InfrastructureLayerServices
services.AddSingleton<IHashService, HashService>();
services.AddSingleton<ICryptographyService, CryptographyService>();
services.AddSingleton<IJwtTokenGenerator, JwtTokenGenerator>();
services.AddSingleton<IQRCodeGenerator, QRCodeGenerator>();
services.AddSingleton<ITokenGenerator, TokenGenerator>();
services.AddSingleton<ITotpTokenGenerator, TotpTokenGenerator>();
services.AddSingleton<IDateTimeProvider, DateTimeProvider>();
return services;
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Infrastructure.Common.Models.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
#endregion
namespace Lumina.Infrastructure.Core.Authentication;
/// <summary>
/// Class for generating JWT tokens.
/// </summary>
public class JwtTokenGenerator : IJwtTokenGenerator
{
private readonly IDateTimeProvider _dateTimeProvider;
private readonly JwtSettingsModel _jwtSettingsModel;
/// <summary>
/// Initializes a new instance of the <see cref="JwtTokenGenerator"/> class.
/// </summary>
/// <param name="dateTimeProvider">Injected service for time related functionality.</param>
/// <param name="jwtSettingsModelOptions">Injected service for retrieving <see cref="JwtSettingsModel"/>.</param>
public JwtTokenGenerator(IDateTimeProvider dateTimeProvider, IOptions<JwtSettingsModel> jwtSettingsModelOptions)
{
_dateTimeProvider = dateTimeProvider;
_jwtSettingsModel = jwtSettingsModelOptions.Value;
}
/// <summary>
/// Generates a new JWT token.
/// </summary>
/// <param name="id">The id of the user for which to generate the token.</param>
/// <param name="username">The username of the user for which to generate the token.</param>
/// <returns>The generated JWT token.</returns>
public string GenerateToken(string id, string username)
{
// use a symmetric key approach
SigningCredentials signingCredentials = new(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettingsModel.SecretKey)), SecurityAlgorithms.HmacSha256);
Claim[] claims =
[
new Claim(JwtRegisteredClaimNames.Sub, id),
new Claim(JwtRegisteredClaimNames.UniqueName, username),
new Claim(JwtRegisteredClaimNames.Jti, id.ToString())
];
JwtSecurityToken securityToken = new(
issuer: _jwtSettingsModel.Issuer,
audience: _jwtSettingsModel.Audience,
expires: _dateTimeProvider.UtcNow.AddMinutes(_jwtSettingsModel.ExpiryMinutes),
claims: claims,
signingCredentials: signingCredentials);
return new JwtSecurityTokenHandler().WriteToken(securityToken);
}
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authentication;
using OtpNet;
using QRCoder;
using System;
#endregion
namespace Lumina.Infrastructure.Core.Authentication;
/// <summary>
/// Service for generating QR codes for TOTP.
/// </summary>
public class QRCodeGenerator : IQRCodeGenerator
{
private const string ISSUER = "Lumina";
/// <summary>
/// Generates a QR code Data URI for the specified TOTP secret.
/// </summary>
/// <param name="username">User's username or unique identifier.</param>
/// <param name="secret">The TOTP secret for which the QR code should be generated.</param>
/// <returns>Data URI for the QR code.</returns>
public string GenerateQrCodeDataUri(string username, byte[] secret)
{
// convert secret to Base32
string base32Secret = Base32Encoding.ToString(secret);
// build the otpauth URI
string otpauthString = $"otpauth://totp/{ISSUER}:{Uri.EscapeDataString(username)}?secret={base32Secret}&issuer={ISSUER}";
// generate QR Code
QRCoder.QRCodeGenerator qrGenerator = new();
QRCodeData qrData = qrGenerator.CreateQrCode(otpauthString, QRCoder.QRCodeGenerator.ECCLevel.Q);
PngByteQRCode qrCode = new(qrData);
// convert QR Code to Data URI
byte[] pngBytes = qrCode.GetGraphic(20); // specify a pixel size if needed
string dataUri = "data:image/png;base64," + Convert.ToBase64String(pngBytes);
return dataUri;
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authentication;
using System;
using System.Security.Cryptography;
#endregion
namespace Lumina.Infrastructure.Core.Authentication;
/// <summary>
/// Service for the service for generating secure tokens for accounts confirmation or recovery.
/// </summary>
public class TokenGenerator : ITokenGenerator
{
/// <summary>
/// Generates a secure token.
/// </summary>
/// <returns>A secure token.</returns>
public string GenerateToken()
{
// allocate an array for the token data
byte[] tokenData = new byte[32];
// fill the array with a cryptographically strong sequence of random values
RandomNumberGenerator.Fill(tokenData);
// convert to a Base64 string, but replace URL-unsafe characters '+' and '/' with '-' and '_', and remove padding characters ('=')
return Convert.ToBase64String(tokenData).Replace('+', '-').Replace('/', '_').TrimEnd('=');
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authentication;
using OtpNet;
#endregion
namespace Lumina.Infrastructure.Core.Authentication;
/// <summary>
/// Service for generating and validating TOTP tokens.
/// </summary>
public class TotpTokenGenerator : ITotpTokenGenerator
{
/// <summary>
/// Generates a new TOTP secret for a user.
/// </summary>
/// <returns>The generated TOTP secret.</returns>
public byte[] GenerateSecret()
{
return KeyGeneration.GenerateRandomKey(); // generate a random key for TOTP
}
/// <summary>
/// Validates a TOTP token against the stored secret.
/// </summary>
/// <param name="secret">The user's TOTP secret.</param>
/// <param name="token">The token to validate.</param>
/// <returns><see langword="true"/> if valid, <see langword="false"/> otherwise.</returns>
public bool ValidateToken(byte[] secret, string token)
{
Totp totp = new(secret);
// verify the TOTP token, allowing for slight time drifts between server and client
return totp.VerifyTotp(token, out _, VerificationWindow.RfcSpecifiedNetworkDelay);
}
}
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Infrastructure.Common.Models.Configuration;
using Microsoft.Extensions.Options;
using System;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Konscious.Security.Cryptography;
using Lumina.Application.Common.Infrastructure;
using Lumina.Application.Common.Infrastructure.Security;
using System;
using System.Security.Cryptography;
using System.Text;
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Time;
using System;
#endregion
namespace Lumina.Infrastructure.Core.Time;
/// <summary>
/// Service for time related concerns
/// </summary>
public class DateTimeProvider : IDateTimeProvider
{
/// <summary>
/// The current UTC time.
/// </summary>
public DateTime UtcNow => DateTime.UtcNow;
}
@@ -20,6 +20,9 @@
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
<PackageReference Include="Otp.NET" Version="1.4.0" />
<PackageReference Include="QRCoder" Version="1.6.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.2.0" />
</ItemGroup>
<ItemGroup>