Simplifies and centralizes authorization for attributes, codes and views

This commit is contained in:
BinaryAlley committed 2024-12-09 09:09:48 +02:00
1 parent 8eb1b9f13c
commit 80f27eb24b
4 files changed
+157 -55

No files matched your search

@@ -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;
/// <summary>
/// Interface for the service for managing authorization.
/// </summary>
public interface IAuthorizationService
{
/// <summary>
/// Determines whether the currently logged in user has a specific permission.
/// </summary>
/// <param name="permission">The permission to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the currently logged in user has the specified permission, <see langword="false"/> otherwise.</returns>
Task<bool> HasPermissionAsync(AuthorizationPermission permission, CancellationToken cancellationToken);
/// <summary>
/// Determines whether the currently logged in user belongs to a specific role.
/// </summary>
/// <param name="role">The role to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the currently logged in user is in the specified role, <see langword="false"/> otherwise.</returns>
Task<bool> IsInRoleAsync(AuthorizationRole role, CancellationToken cancellationToken);
/// <summary>
/// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization policy.
/// </summary>
/// <typeparam name="TAuthorizationPolicy">The type of authorization policy to evaluate.</typeparam>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the currently logged in user satisfies the policy, <see langword="false"/> otherwise.</returns>
Task<bool> EvaluatePolicyAsync<TAuthorizationPolicy>(CancellationToken cancellationToken);
/// <summary>
/// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization requirement.
/// </summary>
/// <param name="requirement">The authorization requirements to check.</param>
/// <returns><see langword="true"/> if the currently logged in user satisfies the requirement, <see langword="false"/> otherwise.</returns>
Task<bool> EvaluateAuthorizationAsync(AuthorizationRequirementModel requirement);
}
@@ -218,6 +218,7 @@ public static class PresentationWebLayerServices
services.AddScoped<ApiExceptionFilter>();
services.AddScoped<IAuthorizationHandler, InitializationHandler>();
services.AddScoped<Authorization.IAuthorizationService, AuthorizationService>();
services.AddSingleton<ICryptographyService, CryptographyService>();
services.AddSingleton<IUrlService, UrlService>();
services.AddHybridCache(); // used for caching authorization roles, permissions and policies
@@ -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;
/// </summary>
public class ApiAuthorizationFilter : IAsyncAuthorizationFilter
{
private readonly IApiHttpClient _apiHttpClient;
private readonly IAuthorizationService _authorizationService;
private readonly AuthorizationRequirementModel _requirement;
/// <summary>
/// Initializes a new instance of the <see cref="ApiAuthorizationFilter"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
/// <param name="authorizationService">Injected service for interactions with the API.</param>
/// <param name="requirement">Authorization requirements to evaluate.</param>
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
/// <param name="context">The authorization filter context.</param>
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();
}
}
/// <summary>
/// Retrieves user authorization details from the authorization service.
/// </summary>
/// <param name="userId">The Id of the user to get authorization for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The user's authorization details.</returns>
private async Task<GetAuthorizationResponse> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken)
{
return await _apiHttpClient.GetAsync<GetAuthorizationResponse>($"auth/get-authorization?userId={Uri.EscapeDataString(userId.ToString())}", cancellationToken);
}
/// <summary>
/// Evaluates if the user meets all authorization requirements.
/// </summary>
/// <param name="authorization">The user's authorization details.</param>
/// <returns><see langword="true"/> if the user meets all requirements, <see langword="false"/> otherwise.</returns>
private async Task<bool> 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<bool, object>($"auth/evaluate-policy/{_requirement.PolicyType.Name}", null!);
// if (!response)
// return false;
//}
await Task.CompletedTask;
return true;
}
}
@@ -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;
/// <summary>
/// Implements authorization logic for API endpoints by validating user roles, permissions, and policies.
/// </summary>
public class AuthorizationService : IAuthorizationService
{
private readonly IApiHttpClient _apiHttpClient;
private readonly IHttpContextAccessor _httpContextAccessor;
/// <summary>
/// Initializes a new instance of the <see cref="AuthorizationService"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected HTTP typed client for interactions with the API.</param>
/// <param name="httpContextAccessor">The <see cref="IHttpContextAccessor"/> used to access the current HTTP context.</param>
public AuthorizationService(IApiHttpClient apiHttpClient, IHttpContextAccessor httpContextAccessor)
{
_apiHttpClient = apiHttpClient;
_httpContextAccessor = httpContextAccessor;
}
/// <summary>
/// Determines whether the currently logged in user has a specific permission.
/// </summary>
/// <param name="permission">The permission to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the currently logged in user has the specified permission, <see langword="false"/> otherwise.</returns>
public async Task<bool> HasPermissionAsync(AuthorizationPermission permission, CancellationToken cancellationToken)
{
GetAuthorizationResponse authorization = await GetUserAuthorizationAsync(cancellationToken).ConfigureAwait(false);
return authorization.Permissions.Contains(permission);
}
/// <summary>
/// Determines whether the currently logged in user belongs to a specific role.
/// </summary>
/// <param name="role">The role to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the currently logged in user is in the specified role, <see langword="false"/> otherwise.</returns>
public async Task<bool> IsInRoleAsync(AuthorizationRole role, CancellationToken cancellationToken)
{
GetAuthorizationResponse authorization = await GetUserAuthorizationAsync(cancellationToken).ConfigureAwait(false);
return authorization.Roles.Contains(role);
}
/// <summary>
/// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization policy.
/// </summary>
/// <typeparam name="TAuthorizationPolicy">The type of authorization policy to evaluate.</typeparam>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the currently logged in user satisfies the policy, <see langword="false"/> otherwise.</returns>
public Task<bool> EvaluatePolicyAsync<TAuthorizationPolicy>(CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
/// <summary>
/// Evaluates whether the currently logged in user meets the conditions defined in the specified authorization requirement.
/// </summary>
/// <param name="requirement">The authorization requirements to check.</param>
/// <returns><see langword="true"/> if the currently logged in user satisfies the requirement, <see langword="false"/> otherwise.</returns>
public async Task<bool> 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<bool, object>($"auth/evaluate-policy/{_requirement.PolicyType.Name}", null!);
// if (!response)
// return false;
//}
return true;
}
/// <summary>
/// Retrieves user authorization details from the authorization service.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The user's authorization details.</returns>
private async Task<GetAuthorizationResponse> 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<GetAuthorizationResponse>($"auth/get-authorization?userId={Uri.EscapeDataString(userId.ToString())}", cancellationToken);
}
}