From 9ce6e01be17e5a95a2351c9c906d344340fc04ca Mon Sep 17 00:00:00 2001 From: Jared Goodwin Date: Fri, 31 May 2024 13:17:03 -0700 Subject: [PATCH] Fix two factor enforcement. --- Server/Auth/TwoFactorRequiredHandler.cs | 42 +++++++++++++---------- Server/Components/AuthorizedIndex.razor | 11 ------ Server/Components/Layout/MainLayout.razor | 12 +++++-- 3 files changed, 34 insertions(+), 31 deletions(-) diff --git a/Server/Auth/TwoFactorRequiredHandler.cs b/Server/Auth/TwoFactorRequiredHandler.cs index 0d62fb79..47fb2dfe 100644 --- a/Server/Auth/TwoFactorRequiredHandler.cs +++ b/Server/Auth/TwoFactorRequiredHandler.cs @@ -1,31 +1,21 @@ using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Identity; +using Remotely.Server.Models; using Remotely.Server.Services; -using Remotely.Shared.Entities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using System.Security.Principal; namespace Remotely.Server.Auth; -public class TwoFactorRequiredHandler : AuthorizationHandler +public class TwoFactorRequiredHandler( + IHttpContextAccessor _contextAccessor, + IDataService _dataService) : AuthorizationHandler { - private readonly IDataService _dataService; - - public TwoFactorRequiredHandler(IDataService dataService) - { - _dataService = dataService; - } - protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, TwoFactorRequiredRequirement requirement) { var settings = await _dataService.GetSettings(); - if (context.User.Identity?.IsAuthenticated == true && - context.User.Identity.Name is not null && - settings.Require2FA) + if (context.User?.Identity is { } identity && + IsTwoFactorRequired(identity, settings)) { - var userResult = await _dataService.GetUserByName(context.User.Identity.Name); + var userResult = await _dataService.GetUserByName(identity.Name!); if (!userResult.IsSuccess || !userResult.Value.TwoFactorEnabled) @@ -36,4 +26,20 @@ public class TwoFactorRequiredHandler : AuthorizationHandler @@ -25,7 +26,7 @@

Two-factor authentication is required. Click the button below to set up your authenticator app.

- Enable 2FA +

@@ -42,4 +43,11 @@ - \ No newline at end of file + + +@code { + private void NavigateToTwoFactor() + { + NavMan.NavigateTo("/Account/Manage/TwoFactorAuthentication", true); + } +} \ No newline at end of file