| | | 1 | | using Syki.Back.Auth.Schemes; |
| | | 2 | | using Syki.Back.Domain.Identity; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using System.Collections.Concurrent; |
| | | 5 | | using Microsoft.AspNetCore.Authentication; |
| | | 6 | | using Microsoft.AspNetCore.Authentication.OpenIdConnect; |
| | | 7 | | |
| | | 8 | | namespace Syki.Back.Auth.Managers; |
| | | 9 | | |
| | 0 | 10 | | public class SsoSchemeManager( |
| | 0 | 11 | | SsoEncryptionManager encryption, |
| | 0 | 12 | | IAuthenticationSchemeProvider schemeProvider, |
| | 0 | 13 | | IOptionsMonitorCache<OpenIdConnectOptions> optionsCache, |
| | 0 | 14 | | IEnumerable<IPostConfigureOptions<OpenIdConnectOptions>> postConfigureOptions) |
| | | 15 | | { |
| | 0 | 16 | | private readonly ConcurrentDictionary<string, DateTime> _schemeTimestamps = new(); |
| | | 17 | | |
| | | 18 | | public void RegisterScheme(SsoConfiguration config) |
| | | 19 | | { |
| | 0 | 20 | | RemoveScheme(config.PublicId); |
| | 0 | 21 | | var schemeName = $"{SsoOidcScheme.Prefix}{config.PublicId}"; |
| | | 22 | | |
| | 0 | 23 | | config.ClientSecret = encryption.Decrypt(config.ClientSecret); |
| | | 24 | | |
| | 0 | 25 | | var options = new OpenIdConnectOptions(); |
| | 0 | 26 | | SsoOidcScheme.ConfigureSsoSchemeOptions(options, config); |
| | | 27 | | |
| | 0 | 28 | | foreach (var postConfigure in postConfigureOptions) |
| | | 29 | | { |
| | 0 | 30 | | postConfigure.PostConfigure(schemeName, options); |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | // Options must be cached BEFORE the scheme is registered. |
| | | 34 | | // Otherwise, concurrent requests can trigger the auth middleware to resolve |
| | | 35 | | // default (empty) options via the factory, which TryAdd won't overwrite. |
| | 0 | 36 | | optionsCache.TryAdd(schemeName, options); |
| | 0 | 37 | | schemeProvider.AddScheme(new AuthenticationScheme(schemeName, schemeName, typeof(OpenIdConnectHandler))); |
| | 0 | 38 | | _schemeTimestamps[schemeName] = config.UpdatedAt; |
| | 0 | 39 | | } |
| | | 40 | | |
| | | 41 | | public void RemoveScheme(Guid configExternalId) |
| | | 42 | | { |
| | 0 | 43 | | var schemeName = $"{SsoOidcScheme.Prefix}{configExternalId}"; |
| | 0 | 44 | | schemeProvider.RemoveScheme(schemeName); |
| | 0 | 45 | | optionsCache.TryRemove(schemeName); |
| | 0 | 46 | | _schemeTimestamps.TryRemove(schemeName, out _); |
| | 0 | 47 | | } |
| | | 48 | | |
| | | 49 | | public void UpdateScheme(SsoConfiguration config) |
| | | 50 | | { |
| | 0 | 51 | | RemoveScheme(config.PublicId); |
| | 0 | 52 | | RegisterScheme(config); |
| | 0 | 53 | | } |
| | | 54 | | |
| | | 55 | | public bool IsStale(string schemeName, DateTime dbUpdatedAt) |
| | | 56 | | { |
| | 0 | 57 | | return !_schemeTimestamps.TryGetValue(schemeName, out var cached) || cached < dbUpdatedAt; |
| | | 58 | | } |
| | | 59 | | } |