Files
game-ideas/src/GameIdeas/Client/GameIdeas.BlazorApp/Services/JwtAuthenticationStateProvider.cs
Egamorf 58da2e6843
All checks were successful
Game Ideas deploy / build-test-deploy (push) Successful in 1m13s
Run code clean and fix messages (#45)
Reviewed-on: #45
2025-05-07 01:28:37 +02:00

58 lines
1.9 KiB
C#

using Blazored.LocalStorage;
using GameIdeas.Shared.Constants;
using GameIdeas.Shared.Dto;
using Microsoft.AspNetCore.Components.Authorization;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace GameIdeas.BlazorApp.Services;
public class JwtAuthenticationStateProvider(ILocalStorageService localStorage) : AuthenticationStateProvider
{
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var savedToken = await localStorage.GetItemAsStringAsync(GlobalConstants.LS_AUTH_STORAGE_KEY);
if (!string.IsNullOrWhiteSpace(savedToken))
{
try
{
var token = new JwtSecurityTokenHandler().ReadJwtToken(savedToken);
return new AuthenticationState(
new ClaimsPrincipal(new ClaimsIdentity(token.Claims, "jwt"))
);
}
catch
{
await localStorage.RemoveItemAsync(GlobalConstants.LS_AUTH_STORAGE_KEY);
}
}
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
}
public async Task NotifyUserAuthenticationAsync(TokenDto token)
{
if (token?.Token != null)
{
await localStorage.SetItemAsStringAsync(GlobalConstants.LS_AUTH_STORAGE_KEY, token.Token);
}
if (token?.Expiration != null)
{
await localStorage.SetItemAsStringAsync(GlobalConstants.LS_EXPIRED_STORAGE_KEY, token.Expiration.Value.ToString());
}
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public async Task NotifyUserLogoutAsync()
{
await localStorage.RemoveItemAsync(GlobalConstants.LS_AUTH_STORAGE_KEY);
var nobody = new ClaimsPrincipal(new ClaimsIdentity());
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(nobody)));
}
}