Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Refactor 2fa methods from AuthController to its own controller (#70)

Leendert de Borsta9e41fa6b4f7
diff --git a/src/AliasVault.Api/Controllers/AuthController.cs b/src/AliasVault.Api/Controllers/AuthController.cs
index 2c7e7846f..d3c5042b5 100644
--- a/src/AliasVault.Api/Controllers/AuthController.cs
+++ b/src/AliasVault.Api/Controllers/AuthController.cs
@@ -11,9 +11,7 @@ using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
-using System.Text.Encodings.Web;
using AliasServerDb;
-using AliasVault.Shared.Models;
using AliasVault.Shared.Models.WebApi;
using AliasVault.Shared.Models.WebApi.Auth;
using AliasVault.Shared.Providers.Time;
@@ -24,6 +22,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.IdentityModel.Tokens;
+using SecureRemotePassword;
/// <summary>
/// Auth controller for handling authentication.
@@ -34,11 +33,10 @@ using Microsoft.IdentityModel.Tokens;
/// <param name="configuration">IConfiguration instance.</param>
/// <param name="cache">IMemoryCache instance for persisting SRP values during multi-step login process.</param>
/// <param name="timeProvider">ITimeProvider instance. This returns the time which can be mutated for testing.</param>
-/// <param name="urlEncoder">UrlEncoder instance.</param>
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
[ApiVersion("1")]
-public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFactory, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, UrlEncoder urlEncoder) : ControllerBase
+public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFactory, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider) : ControllerBase
{
/// <summary>
/// Error message for invalid username or password.
@@ -86,143 +84,83 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
[HttpPost("validate")]
public async Task<IActionResult> Validate([FromBody] ValidateLoginRequest model)
{
- var user = await userManager.FindByNameAsync(model.Username);
- if (user == null)
+ var result = await ValidateSrpSession(model.Username, model.ClientPublicEphemeral, model.ClientSessionProof);
+ if (result is null)
{
return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));
}
- if (!cache.TryGetValue(model.Username, out var serverSecretEphemeral) || serverSecretEphemeral is not string)
- {
- return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));
- }
+ var (user, serverSession) = result.Value;
- try
- {
- var serverSession = Cryptography.Srp.DeriveSessionServer(
- serverSecretEphemeral.ToString() ?? string.Empty,
- model.ClientPublicEphemeral,
- user.Salt,
- model.Username,
- user.Verifier,
- model.ClientSessionProof);
-
- // If above does not throw an exception., then the client's proof is valid. Next check if 2FA is required.
- // If 2FA is required, return that status and no token yet.
- if (user.TwoFactorEnabled)
- {
- return Ok(new ValidateLoginResponse(true, string.Empty, null));
- }
-
- // If 2FA is not required, return the token immediately.
- var tokenModel = await GenerateNewTokensForUser(user);
- return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
- }
- catch
+ // If 2FA is required, return that status and no JWT token yet.
+ if (user.TwoFactorEnabled)
{
- return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));
+ return Ok(new ValidateLoginResponse(true, string.Empty, null));
}
+
+ // If 2FA is not required, return the JWT token immediately.
+ var tokenModel = await GenerateNewTokensForUser(user);
+ return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
}
/// <summary>
- /// Validate login including two factor authentication code check.
+ /// Validate login including two-factor authentication code check.
/// </summary>
/// <param name="model">ValidateLoginRequest2Fa model.</param>
/// <returns>Task.</returns>
[HttpPost("validate-2fa")]
public async Task<IActionResult> Validate2Fa([FromBody] ValidateLoginRequest2Fa model)
{
- var user = await userManager.FindByNameAsync(model.Username);
- if (user == null)
- {
- return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));
- }
-
- if (!cache.TryGetValue(model.Username, out var serverSecretEphemeral) || serverSecretEphemeral is not string)
+ var result = await ValidateSrpSession(model.Username, model.ClientPublicEphemeral, model.ClientSessionProof);
+ if (result is null)
{
return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));
}
- try
- {
- var serverSession = Cryptography.Srp.DeriveSessionServer(
- serverSecretEphemeral.ToString() ?? string.Empty,
- model.ClientPublicEphemeral,
- user.Salt,
- model.Username,
- user.Verifier,
- model.ClientSessionProof);
-
- // If above does not throw an exception., then the client's proof is valid. Next check 2-factor code.
-
- // Verify 2-factor code.
- var result = await userManager.VerifyTwoFactorTokenAsync(user, userManager.Options.Tokens.AuthenticatorTokenProvider, model.Code2Fa);
-
- if (!result)
- {
- return BadRequest(ServerValidationErrorResponse.Create(Invalid2FaCode, 400));
- }
+ var (user, serverSession) = result.Value;
- // Generate and return the JWT token.
- var tokenModel = await GenerateNewTokensForUser(user);
- return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
- }
- catch
+ // Verify 2-factor code.
+ var verifyResult = await userManager.VerifyTwoFactorTokenAsync(user, userManager.Options.Tokens.AuthenticatorTokenProvider, model.Code2Fa);
+ if (!verifyResult)
{
- return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));
+ return BadRequest(ServerValidationErrorResponse.Create(Invalid2FaCode, 400));
}
+
+ // Generate and return the JWT token.
+ var tokenModel = await GenerateNewTokensForUser(user);
+ return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
}
/// <summary>
- /// Validate login including two factor authentication recovery code check.
+ /// Validate login including two-factor authentication recovery code check.
/// </summary>
/// <param name="model">ValidateLoginRequestRecoveryCode model.</param>
/// <returns>Task.</returns>
[HttpPost("validate-recovery-code")]
public async Task<IActionResult> ValidateRecoveryCode([FromBody] ValidateLoginRequestRecoveryCode model)
{
- var user = await userManager.FindByNameAsync(model.Username);
- if (user == null)
- {
- return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));
- }
-
- if (!cache.TryGetValue(model.Username, out var serverSecretEphemeral) || serverSecretEphemeral is not string)
+ var result = await ValidateSrpSession(model.Username, model.ClientPublicEphemeral, model.ClientSessionProof);
+ if (result is null)
{
return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));
}
- try
- {
- var serverSession = Cryptography.Srp.DeriveSessionServer(
- serverSecretEphemeral.ToString() ?? string.Empty,
- model.ClientPublicEphemeral,
- user.Salt,
- model.Username,
- user.Verifier,
- model.ClientSessionProof);
-
- // If above does not throw an exception., then the client's proof is valid. Next check 2-factor code.
+ var (user, serverSession) = result.Value;
- // Sanitize recovery code.
- var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty).ToUpper();
+ // Sanitize recovery code.
+ var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty).ToUpper();
- // Attempt to redeem the recovery code
- var result = await userManager.RedeemTwoFactorRecoveryCodeAsync(user, recoveryCode);
+ // Attempt to redeem the recovery code
+ var redeemResult = await userManager.RedeemTwoFactorRecoveryCodeAsync(user, recoveryCode);
- if (!result.Succeeded)
- {
- return BadRequest(ServerValidationErrorResponse.Create(InvalidRecoveryCode, 400));
- }
-
- // Generate and return the JWT token.
- var tokenModel = await GenerateNewTokensForUser(user);
- return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
- }
- catch
+ if (!redeemResult.Succeeded)
{
- return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));
+ return BadRequest(ServerValidationErrorResponse.Create(InvalidRecoveryCode, 400));
}
+
+ // Generate and return the JWT token.
+ var tokenModel = await GenerateNewTokensForUser(user);
+ return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
}
/// <summary>
@@ -235,7 +173,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
{
await using var context = await dbContextFactory.CreateDbContextAsync();
- var principal = GetPrincipalFromExpiredToken(tokenModel.Token);
+ var principal = GetPrincipalFromToken(tokenModel.Token);
if (principal.FindFirst(ClaimTypes.NameIdentifier)?.Value == null)
{
return Unauthorized("User not found (name-1)");
@@ -248,7 +186,6 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
}
// Check if the refresh token is valid.
- // Remove any existing refresh tokens for this user and device.
var deviceIdentifier = GenerateDeviceIdentifier(Request);
var existingToken = context.AliasVaultUserRefreshTokens.FirstOrDefault(t => t.UserId == user.Id && t.DeviceIdentifier == deviceIdentifier);
if (existingToken == null || existingToken.Value != tokenModel.RefreshToken || existingToken.ExpireDate < timeProvider.UtcNow)
@@ -277,104 +214,6 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
return Ok(new TokenModel() { Token = token, RefreshToken = newRefreshToken });
}
- /// <summary>
- /// Get two-factor authentication enabled status for a user.
- /// </summary>
- /// <returns>Task.</returns>
- [HttpGet("status-2fa")]
- public async Task<IActionResult> StatusTwoFactor()
- {
- var user = await userManager.GetUserAsync(User);
- if (user == null)
- {
- return NotFound();
- }
-
- var twoFactorEnabled = await userManager.GetTwoFactorEnabledAsync(user);
- return Ok(new { TwoFactorEnabled = twoFactorEnabled });
- }
-
- /// <summary>
- /// Enable two-factor authentication for a user.
- /// </summary>
- /// <returns>Task.</returns>
- [HttpPost("enable-2fa")]
- public async Task<IActionResult> EnableTwoFactor()
- {
- var user = await userManager.GetUserAsync(User);
- if (user == null)
- {
- return NotFound();
- }
-
- var authenticatorKey = await userManager.GetAuthenticatorKeyAsync(user);
- if (string.IsNullOrEmpty(authenticatorKey))
- {
- await userManager.ResetAuthenticatorKeyAsync(user);
- authenticatorKey = await userManager.GetAuthenticatorKeyAsync(user);
- }
-
- var encodedKey = urlEncoder.Encode(authenticatorKey!);
- var qrCodeUrl = $"otpauth://totp/{urlEncoder.Encode("AliasVault")}:{urlEncoder.Encode(user.UserName!)}?secret={encodedKey}&issuer={urlEncoder.Encode("AliasVault")}";
-
- return Ok(new { Secret = authenticatorKey, QrCodeUrl = qrCodeUrl });
- }
-
- /// <summary>
- /// Disable two-factor authentication for a user.
- /// </summary>
- /// <returns>Task.</returns>
- [HttpPost("disable-2fa")]
- public async Task<IActionResult> DisableTwoFactor()
- {
- var user = await userManager.GetUserAsync(User);
- if (user == null)
- {
- return NotFound();
- }
-
- await using var context = await dbContextFactory.CreateDbContextAsync();
-
- // Disable 2FA and remove any existing authenticator key(s) and recovery codes.
- await userManager.SetTwoFactorEnabledAsync(user, false);
- context.UserTokens.RemoveRange(
- context.UserTokens.Where(
- x => x.UserId == user.Id &&
- (x.Name == "AuthenticatorKey" || x.Name == "RecoveryCodes")).ToList());
-
- await context.SaveChangesAsync();
- return Ok();
- }
-
- /// <summary>
- /// Verify two-factor authentication setup.
- /// </summary>
- /// <param name="code">Code to verify if 2fa successfully works.</param>
- /// <returns>Task.</returns>
- [HttpPost("verify-2fa")]
- public async Task<IActionResult> VerifyTwoFactorSetup([FromBody] string code)
- {
- var user = await userManager.GetUserAsync(User);
- if (user == null)
- {
- return NotFound();
- }
-
- var isValid = await userManager.VerifyTwoFactorTokenAsync(user, userManager.Options.Tokens.AuthenticatorTokenProvider, code);
-
- if (isValid)
- {
- await userManager.SetTwoFactorEnabledAsync(user, true);
-
- // Generate new recovery codes.
- var recoveryCodes = await userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
-
- return Ok(new { RecoveryCodes = recoveryCodes });
- }
-
- return BadRequest("Invalid code.");
- }
-
/// <summary>
/// Revoke endpoint used to revoke a refresh token.
/// </summary>
@@ -385,7 +224,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
{
await using var context = await dbContextFactory.CreateDbContextAsync();
- var principal = GetPrincipalFromExpiredToken(model.Token);
+ var principal = GetPrincipalFromToken(model.Token);
if (principal.FindFirst(ClaimTypes.NameIdentifier)?.Value == null)
{
return Unauthorized("User not found (name-1)");
@@ -456,6 +295,20 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
return rawIdentifier;
}
+ /// <summary>
+ /// Generate a refresh token for a user. This token is used to request a new access token when the current
+ /// access token expires. The refresh token is long-lived by design.
+ /// </summary>
+ /// <returns>Random string to be used as refresh token.</returns>
+ private static string GenerateRefreshToken()
+ {
+ var randomNumber = new byte[32];
+ using var rng = RandomNumberGenerator.Create();
+
+ rng.GetBytes(randomNumber);
+ return Convert.ToBase64String(randomNumber);
+ }
+
/// <summary>
/// Get the JWT key from the environment variables.
/// </summary>
@@ -473,12 +326,12 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
}
/// <summary>
- /// Get the principal from an expired token. This is used to validate the token and extract the user.
+ /// Get the principal from a token. This is used to validate the token and extract the user.
/// </summary>
- /// <param name="token">The expired token as string.</param>
+ /// <param name="token">The token as string.</param>
/// <returns>Claims principal.</returns>
/// <exception cref="SecurityTokenException">Thrown if provided token is invalid.</exception>
- private static ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
+ private static ClaimsPrincipal GetPrincipalFromToken(string token)
{
var tokenValidationParameters = new TokenValidationParameters
{
@@ -486,6 +339,8 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetJwtKey())),
+
+ // We don't validate the token lifetime here, as we only use it for refresh tokens.
ValidateLifetime = false,
};
@@ -500,17 +355,39 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
}
/// <summary>
- /// Generate a refresh token for a user. This token is used to request a new access token when the current
- /// access token expires. The refresh token is long-lived by design.
+ /// Helper method that validates the SRP session based on provided username, ephemeral and proof.
/// </summary>
- /// <returns>Random string to be used as refresh token.</returns>
- private static string GenerateRefreshToken()
+ /// <param name="username">The username.</param>
+ /// <param name="clientEphemeral">The client ephemeral value.</param>
+ /// <param name="clientSessionProof">The client session proof.</param>
+ /// <returns>Tuple.</returns>
+ private async Task<(AliasVaultUser User, SrpSession ServerSession)?> ValidateSrpSession(string username, string clientEphemeral, string clientSessionProof)
{
- var randomNumber = new byte[32];
- using var rng = RandomNumberGenerator.Create();
+ var user = await userManager.FindByNameAsync(username);
+ if (user == null)
+ {
+ return null;
+ }
- rng.GetBytes(randomNumber);
- return Convert.ToBase64String(randomNumber);
+ if (!cache.TryGetValue(username, out var serverSecretEphemeral) || serverSecretEphemeral is not string)
+ {
+ return null;
+ }
+
+ var serverSession = Cryptography.Srp.DeriveSessionServer(
+ serverSecretEphemeral.ToString() ?? string.Empty,
+ clientEphemeral,
+ user.Salt,
+ username,
+ user.Verifier,
+ clientSessionProof);
+
+ if (serverSession is null)
+ {
+ return null;
+ }
+
+ return (user, serverSession);
}
/// <summary>
diff --git a/src/AliasVault.Api/Controllers/TwoFactorAuthController.cs b/src/AliasVault.Api/Controllers/TwoFactorAuthController.cs
new file mode 100644
index 000000000..64f492afc
--- /dev/null
+++ b/src/AliasVault.Api/Controllers/TwoFactorAuthController.cs
@@ -0,0 +1,125 @@
+//-----------------------------------------------------------------------
+// <copyright file="TwoFactorAuthController.cs" company="lanedirt">
+// Copyright (c) lanedirt. All rights reserved.
+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Api.Controllers;
+
+using System.Text.Encodings.Web;
+using AliasServerDb;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// Auth controller for handling authentication.
+/// </summary>
+/// <param name="dbContextFactory">AliasServerDbContext instance.</param>
+/// <param name="userManager">UserManager instance.</param>
+/// <param name="urlEncoder">UrlEncoder instance.</param>
+[Route("api/v{version:apiVersion}/[controller]")]
+[ApiController]
+[ApiVersion("1")]
+public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbContextFactory, UserManager<AliasVaultUser> userManager, UrlEncoder urlEncoder) : ControllerBase
+{
+ /// <summary>
+ /// Get two-factor authentication enabled status for a user.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [HttpGet("status")]
+ public async Task<IActionResult> Status()
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound();
+ }
+
+ var twoFactorEnabled = await userManager.GetTwoFactorEnabledAsync(user);
+ return Ok(new { TwoFactorEnabled = twoFactorEnabled });
+ }
+
+ /// <summary>
+ /// Enable two-factor authentication for a user.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [HttpPost("enable")]
+ public async Task<IActionResult> Enable()
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound();
+ }
+
+ var authenticatorKey = await userManager.GetAuthenticatorKeyAsync(user);
+ if (string.IsNullOrEmpty(authenticatorKey))
+ {
+ await userManager.ResetAuthenticatorKeyAsync(user);
+ authenticatorKey = await userManager.GetAuthenticatorKeyAsync(user);
+ }
+
+ var encodedKey = urlEncoder.Encode(authenticatorKey!);
+ var qrCodeUrl = $"otpauth://totp/{urlEncoder.Encode("AliasVault")}:{urlEncoder.Encode(user.UserName!)}?secret={encodedKey}&issuer={urlEncoder.Encode("AliasVault")}";
+
+ return Ok(new { Secret = authenticatorKey, QrCodeUrl = qrCodeUrl });
+ }
+
+ /// <summary>
+ /// Disable two-factor authentication for a user.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [HttpPost("disable")]
+ public async Task<IActionResult> Disable()
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound();
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ // Disable 2FA and remove any existing authenticator key(s) and recovery codes.
+ await userManager.SetTwoFactorEnabledAsync(user, false);
+ context.UserTokens.RemoveRange(
+ context.UserTokens.Where(
+ x => x.UserId == user.Id &&
+ (x.Name == "AuthenticatorKey" || x.Name == "RecoveryCodes")).ToList());
+
+ await context.SaveChangesAsync();
+ return Ok();
+ }
+
+ /// <summary>
+ /// Verify two-factor authentication setup.
+ /// </summary>
+ /// <param name="code">Code to verify if 2fa successfully works.</param>
+ /// <returns>Task.</returns>
+ [HttpPost("verify")]
+ public async Task<IActionResult> Verify([FromBody] string code)
+ {
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return NotFound();
+ }
+
+ var isValid = await userManager.VerifyTwoFactorTokenAsync(user, userManager.Options.Tokens.AuthenticatorTokenProvider, code);
+
+ if (isValid)
+ {
+ await userManager.SetTwoFactorEnabledAsync(user, true);
+
+ // Generate new recovery codes.
+ var recoveryCodes = await userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
+
+ return Ok(new { RecoveryCodes = recoveryCodes });
+ }
+
+ return BadRequest("Invalid code.");
+ }
+}
diff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Disable2Fa.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Disable2Fa.razor
index c206aa5fc..de469b813 100644
--- a/src/AliasVault.Client/Main/Pages/Settings/Security/Disable2Fa.razor
+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Disable2Fa.razor
@@ -49,7 +49,7 @@ else
// Check on server if 2FA is enabled
if (firstRender)
{
- var response = await Http.GetFromJsonAsync<TwoFactorEnabledResult>("api/v1/Auth/status-2fa");
+ var response = await Http.GetFromJsonAsync<TwoFactorEnabledResult>("api/v1/TwoFactorAuth/status");
if (response is not null)
{
if (!response.TwoFactorEnabled)
@@ -67,7 +67,7 @@ else
private async Task DisableTwoFactor()
{
- var response = await Http.PostAsync("api/v1/Auth/disable-2fa", null);
+ var response = await Http.PostAsync("api/v1/TwoFactorAuth/disable", null);
if (response.IsSuccessStatusCode)
{
GlobalNotificationService.AddSuccessMessage("Two-factor authentication is now successfully disabled.");
diff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Enable2Fa.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Enable2Fa.razor
index 064f579c8..fec7ce7bd 100644
--- a/src/AliasVault.Client/Main/Pages/Settings/Security/Enable2Fa.razor
+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Enable2Fa.razor
@@ -74,7 +74,7 @@ else
if (firstRender)
{
// Get the QR code and secret for the authenticator app.
- var response = await Http.PostAsync("api/v1/Auth/enable-2fa", null);
+ var response = await Http.PostAsync("api/v1/TwoFactorAuth/enable", null);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<TotpSetupResult>();
@@ -100,7 +100,7 @@ else
private async Task VerifySetup()
{
- var response = await Http.PostAsJsonAsync("api/v1/Auth/verify-2fa", VerifyModel.Code);
+ var response = await Http.PostAsJsonAsync("api/v1/TwoFactorAuth/verify", VerifyModel.Code);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<TotpVerifyResult>();
diff --git a/src/AliasVault.Client/Main/Pages/Settings/Security/Security.razor b/src/AliasVault.Client/Main/Pages/Settings/Security/Security.razor
index 83a68b121..1113525d2 100644
--- a/src/AliasVault.Client/Main/Pages/Settings/Security/Security.razor
+++ b/src/AliasVault.Client/Main/Pages/Settings/Security/Security.razor
@@ -60,7 +60,7 @@ else
// Check on server if 2FA is enabled
if (firstRender)
{
- var response = await Http.GetFromJsonAsync<TwoFactorEnabledResult>("api/v1/Auth/status-2fa");
+ var response = await Http.GetFromJsonAsync<TwoFactorEnabledResult>("api/v1/TwoFactorAuth/status");
if (response is not null)
{
TwoFactorEnabled = response.TwoFactorEnabled;
diff --git a/src/Tests/AliasVault.UnitTests/Utilities/SrpArgonEncryptionTests.cs b/src/Tests/AliasVault.UnitTests/Utilities/SrpArgonEncryptionTests.cs
index 1d403e953..d1249f281 100644
--- a/src/Tests/AliasVault.UnitTests/Utilities/SrpArgonEncryptionTests.cs
+++ b/src/Tests/AliasVault.UnitTests/Utilities/SrpArgonEncryptionTests.cs
@@ -131,6 +131,7 @@ public class SrpArgonEncryptionTests
var serverSession = Srp.DeriveSessionServer(serverEphemeral.Secret, clientEphemeral.Public, salt, email, verifier, clientSession.Proof);
// --> send serverSession.Proof to client.
+ Assert.That(serverSession, Is.Not.Null, "Server session is null, likely indicating that the provided password is incorrect.");
// 5. Client verifies the proof.
Srp.VerifySession(clientEphemeral.Public, clientSession, serverSession.Proof);
diff --git a/src/Utilities/Cryptography/Srp.cs b/src/Utilities/Cryptography/Srp.cs
index 2c2258605..14a12cbc7 100644
--- a/src/Utilities/Cryptography/Srp.cs
+++ b/src/Utilities/Cryptography/Srp.cs
@@ -99,16 +99,24 @@ public static class Srp
/// <param name="verifier">Verifier.</param>
/// <param name="clientSessionProof">Client session proof.</param>
/// <returns>SrpSession.</returns>
- public static SrpSession DeriveSessionServer(string serverEphemeralSecret, string clientEphemeralPublic, string salt, string username, string verifier, string clientSessionProof)
+ public static SrpSession? DeriveSessionServer(string serverEphemeralSecret, string clientEphemeralPublic, string salt, string username, string verifier, string clientSessionProof)
{
- var server = new SrpServer();
- return server.DeriveSession(
- serverEphemeralSecret,
- clientEphemeralPublic,
- salt,
- username,
- verifier,
- clientSessionProof);
+ try
+ {
+ var server = new SrpServer();
+ return server.DeriveSession(
+ serverEphemeralSecret,
+ clientEphemeralPublic,
+ salt,
+ username,
+ verifier,
+ clientSessionProof);
+ }
+ catch (System.Security.SecurityException)
+ {
+ // Incorrect password provided, return null.
+ return null;
+ }
}
/// <summary>