mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 17:11:10 +00:00
Implements authentication system
This commit is contained in:
1 parent
38829d64ff
commit
a6dcf65d1c
103 files changed
+2983
-454
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user