Implements authorization caching and check in the web client

This commit is contained in:
BinaryAlley committed 2024-12-06 18:46:48 +02:00
1 parent 7bca5b1ba3
commit 8eb1b9f13c
108 files changed
+5931 -73

No files matched your search

@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Filters.TypeFilters;
using Lumina.Presentation.Web.Common.Models.Authorization;
#endregion
namespace Lumina.Presentation.Web.Common.Attributes;
/// <summary>
/// Attribute that restricts endpoint access to users with specified permissions.
/// </summary>
/// <remarks>
/// Can be applied to controllers or individual actions. Multiple permissions create an OR condition.
/// </remarks>
public class RequirePermissionAttribute : ApiAuthorizationAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="RequirePermissionAttribute"/> class.
/// </summary>
/// <param name="permissions">One or more permissions that are allowed to access the endpoint.</param>
public RequirePermissionAttribute(params AuthorizationPermission[] permissions) : base()
{
Arguments = [new AuthorizationRequirementModel { Permissions = permissions }];
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Filters.TypeFilters;
using Lumina.Presentation.Web.Common.Models.Authorization;
using System;
#endregion
namespace Lumina.Presentation.Web.Common.Attributes;
/// <summary>
/// Attribute that restricts endpoint access based on a custom authorization policy.
/// </summary>
/// <remarks>
/// Can be applied to controllers or individual actions.
/// </remarks>
public class RequirePolicyAttribute : ApiAuthorizationAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="RequirePolicyAttribute"/> class.
/// </summary>
/// <param name="policyType">The type of the authorization policy to apply.</param>
public RequirePolicyAttribute(Type policyType) : base()
{
Arguments = [new AuthorizationRequirementModel { PolicyType = policyType }];
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Filters.TypeFilters;
using Lumina.Presentation.Web.Common.Models.Authorization;
#endregion
namespace Lumina.Presentation.Web.Common.Attributes;
/// <summary>
/// Attribute that restricts endpoint access to users with specified roles.
/// </summary>
/// <remarks>
/// Can be applied to controllers or individual actions. Multiple roles create an OR condition.
/// </remarks>
public class RequireRoleAttribute : ApiAuthorizationAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="RequireRoleAttribute"/> class.
/// </summary>
/// <param name="roles">One or more roles that are allowed to access the endpoint.</param>
public RequireRoleAttribute(params AuthorizationRole[] roles) : base()
{
Arguments = [new AuthorizationRequirementModel { Roles = roles }];
}
}
@@ -3,8 +3,10 @@ using FluentValidation;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Filters;
using Lumina.Presentation.Web.Common.Filters.AuthorizationFilters;
using Lumina.Presentation.Web.Common.Filters.ExceptionFilters;
using Lumina.Presentation.Web.Common.MiddlewareFilters;
using Lumina.Presentation.Web.Common.Models.Authorization;
using Lumina.Presentation.Web.Common.Security;
using Lumina.Presentation.Web.Common.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
@@ -203,9 +205,14 @@ public static class PresentationWebLayerServices
// register the HTTP typed client used for the API interaction
services.AddHttpClient<IApiHttpClient, ApiHttpClient>()
.AddHttpMessageHandler<CachedAuthorizationHandler>()
.AddPolicyHandler(retryPolicy)
.AddPolicyHandler(circuitBreakerPolicy);
services.AddScoped<CachedAuthorizationHandler>();
services.AddScoped<ApiAuthorizationFilter>();
services.AddScoped<AuthorizationRequirementModel>();
// enable access to the current HTTP context in non-controller classes
services.AddHttpContextAccessor();
@@ -213,6 +220,7 @@ public static class PresentationWebLayerServices
services.AddScoped<IAuthorizationHandler, InitializationHandler>();
services.AddSingleton<ICryptographyService, CryptographyService>();
services.AddSingleton<IUrlService, UrlService>();
services.AddHybridCache(); // used for caching authorization roles, permissions and policies
return services;
}
@@ -0,0 +1,12 @@
namespace Lumina.Presentation.Web.Common.Enums.Authorization;
/// <summary>
/// Enumeration for authorization permissions.
/// </summary>
public enum AuthorizationPermission
{
None = 0,
CanViewUsers = 1,
CanDeleteUsers = 2,
CanRegisterUsers = 3
}
@@ -0,0 +1,10 @@
namespace Lumina.Presentation.Web.Common.Enums.Authorization;
/// <summary>
/// Enumeration for authorization roles.
/// </summary>
public enum AuthorizationRole
{
None = 0,
Admin = 1
}
@@ -5,7 +5,7 @@ using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.Filters;
namespace Lumina.Presentation.Web.Common.Filters.ActionFilters;
/// <summary>
/// Attribute that enforces application initialization checks on controller actions.
@@ -0,0 +1,88 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
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
namespace Lumina.Presentation.Web.Common.Filters.AuthorizationFilters;
/// <summary>
/// Implements authorization filter logic for API endpoints by validating user roles, permissions, and policies.
/// </summary>
public class ApiAuthorizationFilter : IAsyncAuthorizationFilter
{
private readonly IApiHttpClient _apiHttpClient;
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="requirement">Authorization requirements to evaluate.</param>
public ApiAuthorizationFilter(IApiHttpClient apiHttpClient, AuthorizationRequirementModel requirement)
{
_apiHttpClient = apiHttpClient;
_requirement = requirement;
}
/// <summary>
/// Performs authorization for the current request.
/// </summary>
/// <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))
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;
}
}
@@ -15,7 +15,7 @@ using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.Filters;
namespace Lumina.Presentation.Web.Common.Filters.ExceptionFilters;
/// <summary>
/// Filters API exceptions and provides centralized handling for API-related errors.
@@ -45,7 +45,7 @@ public class ApiExceptionFilter : IExceptionFilter
// check if the exception is an ApiException
if (context.Exception is ApiException apiException)
{
// Log all available details for debugging/monitoring
// log all available details for debugging/monitoring
_logger.LogError(
apiException,
"API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}",
@@ -73,9 +73,7 @@ public class ApiExceptionFilter : IExceptionFilter
errorMessage.AppendLine($"<b>{_stringLocalizer[apiException.ProblemDetails.Title]}</b><br>");
if (apiException.ProblemDetails.Extensions?.TryGetValue("errors", out JsonElement errorsObj) == true)
{
if (errorsObj.ValueKind == JsonValueKind.Object)
{
foreach (JsonProperty error in errorsObj.EnumerateObject())
{
_logger.LogError("Validation error {Field}: {@ErrorValues}", error.Name, error.Value.EnumerateArray().Select(jsonElement => jsonElement.ToString()));
@@ -83,8 +81,6 @@ public class ApiExceptionFilter : IExceptionFilter
foreach (JsonElement errorValue in error.Value.EnumerateArray())
errorMessage.AppendLine($"{_stringLocalizer[errorValue.ToString()]}<br>");
}
}
}
}
else
{
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Filters.AuthorizationFilters;
using Microsoft.AspNetCore.Mvc;
using System;
#endregion
namespace Lumina.Presentation.Web.Common.Filters.TypeFilters;
/// <summary>
/// Authorization filter for API endpoints.
/// </summary>
/// <remarks>
/// This attribute can be applied to both classes and methods and supports multiple instances on the same target.
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class ApiAuthorizationAttribute : TypeFilterAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="ApiAuthorizationAttribute"/> class.
/// </summary>
public ApiAuthorizationAttribute() : base(typeof(ApiAuthorizationFilter))
{
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using System;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Authorization;
/// <summary>
/// Model for storing the authorization requirements for accessing a resource.
/// </summary>
public class AuthorizationRequirementModel
{
/// <summary>
/// The collection of roles required for accessing the resource.
/// </summary>
public AuthorizationRole[]? Roles { get; set; }
/// <summary>
/// The collection of permissions required for accessing the resource.
/// </summary>
public AuthorizationPermission[]? Permissions { get; set; }
/// <summary>
/// The type of the policy required for accessing the resource.
/// </summary>
public Type? PolicyType { get; set; }
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Authorization;
/// <summary>
/// Represents the response model for an account authorization request.
/// </summary>
/// <param name="UserId">The Id of the user for whom the authorization is retrieved.</param>
/// <param name="Roles">The collection of roles associated to the user.</param>
/// <param name="Permissions">The collection of permissions associated to the user.</param>
[DebuggerDisplay("UserId: {UserId}")]
public record GetAuthorizationResponse(
Guid UserId,
AuthorizationRole[] Roles,
AuthorizationPermission[] Permissions
);
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.Services;
/// <summary>
/// Delegating handler that intercepts HTTP requests to an authorization endpoint and caches the response. All other requests are forwarded directly.
/// </summary>
public class CachedAuthorizationHandler : DelegatingHandler
{
private readonly HybridCache _hybridCache;
private const string AUTHORIZATION_ENDPOINT = "/auth/get-authorization";
/// <summary>
/// Initializes a new instance of the <see cref="CachedAuthorizationHandler"/> class with the specified hybrid cache.
/// </summary>
/// <param name="hybridCache">The hybrid caching mechanism to store and retrieve authorization responses.</param>
public CachedAuthorizationHandler(HybridCache hybridCache)
{
_hybridCache = hybridCache;
}
/// <summary>
/// Processes HTTP requests and intercepts calls to the authorization endpoint to provide a cached response.
/// Other requests are forwarded to the next handler in the pipeline.
/// </summary>
/// <param name="request">The HTTP request message to process.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The HTTP response message from either the cache or the original API call.</returns>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// get the called API endpoint
string requestPath = request.RequestUri!.AbsolutePath;
// if it's any endpoint other than the one for the authorization request, fire it away towards the original API service
if (!requestPath.EndsWith(AUTHORIZATION_ENDPOINT, StringComparison.OrdinalIgnoreCase))
return await base.SendAsync(request, cancellationToken);
// otherwise, check the hybrid cache to see if there is a cached authorization
string response = await _hybridCache.GetOrCreateAsync(
AUTHORIZATION_ENDPOINT,
async (cancellationToken) =>
{
// perform the actual API call if cache is empty or expired
HttpResponseMessage result = await base.SendAsync(request, cancellationToken);
return await result.Content.ReadAsStringAsync(cancellationToken);
},
new HybridCacheEntryOptions()
{
Expiration = TimeSpan.FromMinutes(5) // cache for the next five minutes
},
cancellationToken: cancellationToken
);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(response)
};
}
}