DotBased/DotBased.ASP.Auth/BasedServerAuthenticationStateProvider.cs

39 lines
1.6 KiB
C#
Raw Normal View History

using System.Security.Claims;
2024-11-02 01:57:25 +01:00
using DotBased.ASP.Auth.Services;
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(typeof(BasedServerAuthenticationStateProvider));
}
private BasedAuthConfiguration _config;
2024-11-04 15:45:38 +01:00
private readonly ProtectedLocalStorage _localStorage;
private readonly SecurityService _securityService;
private 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()
{
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;
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;
}
}