80 lines
3.0 KiB
C#
80 lines
3.0 KiB
C#
using System.Security.Claims;
|
|
using FoodsharingSiegen.Contracts;
|
|
using FoodsharingSiegen.Server.Auth;
|
|
using FoodsharingSiegen.Shared.Helper;
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
|
|
|
namespace FoodsharingSiegen.Server.Service
|
|
{
|
|
/// <summary>
|
|
/// The token auth state provider class (a. beging, 02.04.2022)
|
|
/// </summary>
|
|
/// <seealso cref="AuthenticationStateProvider"/>
|
|
public class TokenAuthStateProvider : AuthenticationStateProvider
|
|
{
|
|
#region Private Fields
|
|
|
|
/// <summary> LocalStorageService </summary>
|
|
private readonly LocalStorageService _localStorageService;
|
|
|
|
#endregion
|
|
|
|
#region Setup/Teardown
|
|
|
|
/// <summary>
|
|
/// Constructor
|
|
/// </summary>
|
|
/// <param name="localStorageService"></param>
|
|
public TokenAuthStateProvider(LocalStorageService localStorageService) => _localStorageService = localStorageService;
|
|
|
|
#endregion
|
|
|
|
#region Override GetAuthenticationStateAsync
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
/// <summary> Get the current authenticationstate </summary>
|
|
/// <remarks> A. Beging, 02.02.2022. </remarks>
|
|
////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
|
|
{
|
|
var token = await _localStorageService.GetItem<string>(StorageKeys.TokenKey);
|
|
var tokenValid = AuthHelper.ValidateToken(token, out _);
|
|
|
|
var identity = new ClaimsIdentity();
|
|
if (tokenValid)
|
|
identity = new ClaimsIdentity(new[]
|
|
{
|
|
new Claim(ClaimTypes.Name, "user")
|
|
}, "TODO");
|
|
|
|
var claimsPrincipal = new ClaimsPrincipal(identity);
|
|
return new AuthenticationState(claimsPrincipal);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Public Method MarkUserAsAuthenticated
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
/// <summary> Mark user as authenticated. </summary>
|
|
/// <remarks> A. Beging, 02.02.2022. </remarks>
|
|
////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
public void MarkUserAsAuthenticated() => NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
|
|
|
#endregion
|
|
|
|
#region Public Method MarkUserAsLoggedOut
|
|
|
|
/// <summary>
|
|
/// Marks the user as logged out (a. beging, 02.04.2022)
|
|
/// </summary>
|
|
public void MarkUserAsLoggedOut()
|
|
{
|
|
var anonymousUser = new ClaimsPrincipal(new ClaimsIdentity());
|
|
var authState = Task.FromResult(new AuthenticationState(anonymousUser));
|
|
NotifyAuthenticationStateChanged(authState);
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
} |