From 4c001d408766e55ec1912d753d9b8b2a6e98e355 Mon Sep 17 00:00:00 2001 From: Developer 02 Date: Wed, 5 Mar 2025 13:06:07 +0100 Subject: [PATCH] feat(AuthHub): Added GetPublicKeyAsync method to send the key to caller --- src/DigitalData.Auth.API/Hubs/AuthHub.cs | 37 ++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/DigitalData.Auth.API/Hubs/AuthHub.cs b/src/DigitalData.Auth.API/Hubs/AuthHub.cs index 3d67c6a..6abd185 100644 --- a/src/DigitalData.Auth.API/Hubs/AuthHub.cs +++ b/src/DigitalData.Auth.API/Hubs/AuthHub.cs @@ -1,10 +1,47 @@ using DigitalData.Auth.Abstractions; +using DigitalData.Core.Abstractions.Security; using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Caching.Memory; namespace DigitalData.Auth.API.Hubs; public class AuthHub : Hub, IAuthSenderHandler { + private readonly ICryptoFactory _cFactory; + + private readonly ILogger _logger; + + private readonly IMemoryCache _cache; + + private readonly static string CacheId = Guid.NewGuid().ToString(); + + public AuthHub(ICryptoFactory cryptoFactory, ILogger logger, IMemoryCache cache) + { + _cFactory = cryptoFactory; + _logger = logger; + _cache = cache; + } + + public async Task GetPublicKeyAsync(string issuer, string audience) + { + if(_cFactory.TokenDescriptors.TryGet(issuer, audience, out var tDesc)) + { + await Clients.Caller.ReceivePublicKeyAsync(issuer, audience, tDesc.PublicKey.Content); + } + else + { + await Clients.Caller.ReceivePublicKeyAsync(issuer, audience, string.Empty); + + // Log this warning only once per minute to avoid unnecessary repetition. + _cache.GetOrCreate(CacheId + "LastLoggingDate", e => + { + _logger.LogWarning("Token description is not found. Issuer: {issuer} Audience: {audience}", issuer, audience); + e.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1); + return true; + }); + } + } + public async Task SendPublicKeyAsync(string issuer, string audience, string value) => await Clients.All.ReceivePublicKeyAsync(issuer, audience, value); } \ No newline at end of file