DotBased/DotBased.ASP.Auth/BasedServerAuthenticationStateProvider.cs

40 lines
1.8 KiB
C#
Raw Permalink Normal View History

using System.Security.Claims;
using DotBased.Logging;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
2024-11-02 01:57:25 +01:00
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using ILogger = DotBased.Logging.ILogger;
namespace DotBased.ASP.Auth;
// RevalidatingServerAuthenticationStateProvider
// AuthenticationStateProvider
2024-10-14 15:28:43 +02:00
// Handles roles
public class BasedServerAuthenticationStateProvider : ServerAuthenticationStateProvider
{
2024-11-02 01:57:25 +01:00
public BasedServerAuthenticationStateProvider(BasedAuthConfiguration configuration, ProtectedLocalStorage localStorage, SecurityService securityService)
{
_config = configuration;
2024-11-02 01:57:25 +01:00
_localStorage = localStorage;
_securityService = securityService;
_logger = LogService.RegisterLogger<BasedServerAuthenticationStateProvider>();
}
private BasedAuthConfiguration _config;
2024-11-04 15:45:38 +01:00
private readonly ProtectedLocalStorage _localStorage;
private readonly SecurityService _securityService;
private readonly ILogger _logger;
2024-11-04 15:45:38 +01:00
private readonly AuthenticationState _anonState = new(new ClaimsPrincipal());
2024-10-14 15:28:43 +02:00
2024-11-02 01:57:25 +01:00
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
_logger.Debug("Getting authentication state...");
2024-11-04 15:45:38 +01:00
var sessionIdResult = await _localStorage.GetAsync<string>(BasedAuthDefaults.StorageKey);
2024-11-02 01:57:25 +01:00
if (!sessionIdResult.Success || sessionIdResult.Value == null)
return _anonState;
_logger.Debug("Found state [{State}], getting session from {Service}", sessionIdResult.Value, nameof(SecurityService));
2024-11-04 15:45:38 +01:00
var stateResult = await _securityService.GetAuthenticationStateFromSessionAsync(sessionIdResult.Value);
2024-11-02 01:57:25 +01:00
return stateResult is { Success: true, Value: not null } ? stateResult.Value : _anonState;
}
}