diff --git a/src/Lumina.Presentation.Web/Common/Authorization/IAuthorizationService.cs b/src/Lumina.Presentation.Web/Common/Authorization/IAuthorizationService.cs new file mode 100644 index 00000000..651bb67b --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Authorization/IAuthorizationService.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Models.Authorization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Authorization; + +/// +/// Interface for the service for managing authorization. +/// +public interface IAuthorizationService +{ + /// + /// Determines whether the currently logged in user has a specific permission. + /// + /// The permission to check. + /// Cancellation token that can be used to stop the execution. + /// if the currently logged in user has the specified permission, otherwise. + Task HasPermissionAsync(AuthorizationPermission permission, CancellationToken cancellationToken); + + /// + /// Determines whether the currently logged in user belongs to a specific role. + /// + /// The role to check. + /// Cancellation token that can be used to stop the execution. + /// if the currently logged in user is in the specified role, otherwise. + Task IsInRoleAsync(AuthorizationRole role, CancellationToken cancellationToken); + + /// + /// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization policy. + /// + /// The type of authorization policy to evaluate. + /// Cancellation token that can be used to stop the execution. + /// if the currently logged in user satisfies the policy, otherwise. + Task EvaluatePolicyAsync(CancellationToken cancellationToken); + + /// + /// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization requirement. + /// + /// The authorization requirements to check. + /// if the currently logged in user satisfies the requirement, otherwise. + Task EvaluateAuthorizationAsync(AuthorizationRequirementModel requirement); +} diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 8300bb74..c607976d 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -218,6 +218,7 @@ public static class PresentationWebLayerServices services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddSingleton(); services.AddSingleton(); services.AddHybridCache(); // used for caching authorization roles, permissions and policies diff --git a/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs b/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs index 61a1e6f2..cb2c1db9 100644 --- a/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs +++ b/src/Lumina.Presentation.Web/Common/Filters/AuthorizationFilters/ApiAuthorizationFilter.cs @@ -1,12 +1,8 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Models.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; -using System; -using System.Linq; -using System.Security.Claims; -using System.Threading; using System.Threading.Tasks; #endregion @@ -17,17 +13,17 @@ namespace Lumina.Presentation.Web.Common.Filters.AuthorizationFilters; /// public class ApiAuthorizationFilter : IAsyncAuthorizationFilter { - private readonly IApiHttpClient _apiHttpClient; + private readonly IAuthorizationService _authorizationService; private readonly AuthorizationRequirementModel _requirement; /// /// Initializes a new instance of the class. /// - /// Injected service for interactions with the API. + /// Injected service for interactions with the API. /// Authorization requirements to evaluate. - public ApiAuthorizationFilter(IApiHttpClient apiHttpClient, AuthorizationRequirementModel requirement) + public ApiAuthorizationFilter(IAuthorizationService authorizationService, AuthorizationRequirementModel requirement) { - _apiHttpClient = apiHttpClient; + _authorizationService = authorizationService; _requirement = requirement; } @@ -37,52 +33,7 @@ public class ApiAuthorizationFilter : IAsyncAuthorizationFilter /// The authorization filter context. public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { - // get the id of the currently logged in user - Claim? currentUserIdClaim = context.HttpContext.User?.FindFirst(ClaimTypes.NameIdentifier); - // if a valid user id cannot be retrieved, authorization fails - if (currentUserIdClaim is null || string.IsNullOrWhiteSpace(currentUserIdClaim.Value) || !Guid.TryParse(currentUserIdClaim.Value, out Guid currentUserId)) + if (!await _authorizationService.EvaluateAuthorizationAsync(_requirement)) context.Result = new ForbidResult(); - else - { - // ask the API for the user's authorization details - GetAuthorizationResponse userAuthorization = await GetUserAuthorizationAsync(currentUserId, context.HttpContext.RequestAborted); - // if the user's authorization details don't satisfy the requested authorization details, deny the request - if (!await EvaluateAuthorizationAsync(userAuthorization)) - context.Result = new ForbidResult(); - } - } - - /// - /// Retrieves user authorization details from the authorization service. - /// - /// The Id of the user to get authorization for. - /// Cancellation token that can be used to stop the execution. - /// The user's authorization details. - private async Task GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken) - { - return await _apiHttpClient.GetAsync($"auth/get-authorization?userId={Uri.EscapeDataString(userId.ToString())}", cancellationToken); - } - - /// - /// Evaluates if the user meets all authorization requirements. - /// - /// The user's authorization details. - /// if the user meets all requirements, otherwise. - private async Task EvaluateAuthorizationAsync(GetAuthorizationResponse authorization) - { - if (_requirement.Roles?.Length > 0 && !_requirement.Roles.Any(role => authorization.Roles?.Contains(role) == true)) - return false; - - if (_requirement.Permissions?.Length > 0 && !_requirement.Permissions.Any(permission => authorization.Permissions.Contains(permission))) - return false; - - //if (_requirement.PolicyType is not null) - //{ - // bool response = await _apiHttpClient.PostAsync($"auth/evaluate-policy/{_requirement.PolicyType.Name}", null!); - // if (!response) - // return false; - //} - await Task.CompletedTask; - return true; } } diff --git a/src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationService.cs b/src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationService.cs new file mode 100644 index 00000000..1ecc0a7f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Authorization/AuthorizationService.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Microsoft.AspNetCore.Http; +using System; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.Authorization; + +/// +/// Implements authorization logic for API endpoints by validating user roles, permissions, and policies. +/// +public class AuthorizationService : IAuthorizationService +{ + private readonly IApiHttpClient _apiHttpClient; + private readonly IHttpContextAccessor _httpContextAccessor; + + /// + /// Initializes a new instance of the class. + /// + /// Injected HTTP typed client for interactions with the API. + /// The used to access the current HTTP context. + public AuthorizationService(IApiHttpClient apiHttpClient, IHttpContextAccessor httpContextAccessor) + { + _apiHttpClient = apiHttpClient; + _httpContextAccessor = httpContextAccessor; + } + + /// + /// Determines whether the currently logged in user has a specific permission. + /// + /// The permission to check. + /// Cancellation token that can be used to stop the execution. + /// if the currently logged in user has the specified permission, otherwise. + public async Task HasPermissionAsync(AuthorizationPermission permission, CancellationToken cancellationToken) + { + GetAuthorizationResponse authorization = await GetUserAuthorizationAsync(cancellationToken).ConfigureAwait(false); + return authorization.Permissions.Contains(permission); + } + + /// + /// Determines whether the currently logged in user belongs to a specific role. + /// + /// The role to check. + /// Cancellation token that can be used to stop the execution. + /// if the currently logged in user is in the specified role, otherwise. + public async Task IsInRoleAsync(AuthorizationRole role, CancellationToken cancellationToken) + { + GetAuthorizationResponse authorization = await GetUserAuthorizationAsync(cancellationToken).ConfigureAwait(false); + return authorization.Roles.Contains(role); + } + + /// + /// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization policy. + /// + /// The type of authorization policy to evaluate. + /// Cancellation token that can be used to stop the execution. + /// if the currently logged in user satisfies the policy, otherwise. + public Task EvaluatePolicyAsync(CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } + + /// + /// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization requirement. + /// + /// The authorization requirements to check. + /// if the currently logged in user satisfies the requirement, otherwise. + public async Task EvaluateAuthorizationAsync(AuthorizationRequirementModel requirement) + { + GetAuthorizationResponse authorization = await GetUserAuthorizationAsync(CancellationToken.None); + + if (requirement.Roles?.Length > 0 && !requirement.Roles.Any(role => authorization.Roles?.Contains(role) == true)) + return false; + + if (requirement.Permissions?.Length > 0 && !requirement.Permissions.Any(permission => authorization.Permissions.Contains(permission))) + return false; + + //if (_requirement.PolicyType is not null) + //{ + // bool response = await _apiHttpClient.PostAsync($"auth/evaluate-policy/{_requirement.PolicyType.Name}", null!); + // if (!response) + // return false; + //} + + return true; + } + + /// + /// Retrieves user authorization details from the authorization service. + /// + /// Cancellation token that can be used to stop the execution. + /// The user's authorization details. + private async Task GetUserAuthorizationAsync(CancellationToken cancellationToken) + { + // get the id of the currently logged in user + string userId = _httpContextAccessor.HttpContext!.User.FindFirst(ClaimTypes.NameIdentifier)!.Value; + return await _apiHttpClient.GetAsync($"auth/get-authorization?userId={Uri.EscapeDataString(userId.ToString())}", cancellationToken); + } +}