laatzen/LaaProductionWeb/LaaProductionWeb.Blazor/Components/Identity/Services/IdentityService.cs
2025-03-17 16:03:24 +01:00

46 lines
1.6 KiB
C#

namespace LaaProductionWeb.Blazor.Components.Identity.Services
{
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
public class IdentityService(ProtectedLocalStorage protectedLocalStorage, IdentityJwtService jwtService, ILogger<IdentityService> logger)
{
private readonly ProtectedLocalStorage protectedLocalStorage = protectedLocalStorage;
private readonly IdentityJwtService jwtService = jwtService;
private readonly ILogger<IdentityService> logger = logger;
public async Task<ClaimsPrincipal> GetClaimsPrincipalAsync()
{
var claimsIdentity = new ClaimsIdentity();
try
{
var tokenResult = await this.protectedLocalStorage
.GetAsync<string>(typeof(Program).Namespace, "JWT");
var token = tokenResult.Success ? tokenResult.Value : default;
var claims = this.jwtService.GetClaims(token);
if (claims.Any())
{
claimsIdentity = new ClaimsIdentity(
claims: claims
, authenticationType: ClaimTypes.NameIdentifier
, nameType: ClaimTypes.Name
, roleType: ClaimTypes.Role);
}
}
catch (Exception e)
{
this.logger.LogError(e, e.Message);
}
return new ClaimsPrincipal(claimsIdentity);
}
}
}