using AyCode.Interfaces.StorageHandlers; using Microsoft.AspNetCore.Components.Authorization; using Newtonsoft.Json; using System.IdentityModel.Tokens.Jwt; using System.Net.Http.Headers; using System.Security.Claims; using System.Text.Json; using TIAMWebApp.Shared.Application.Models.ClientSide; namespace TIAMWebApp.Shared.Application.Services { public class CustomAuthStateProvider : AuthenticationStateProvider { private readonly ISecureStorageHandler _localStorage; private readonly HttpClient _http; public CustomAuthStateProvider(ISecureStorageHandler localStorage, HttpClient http) { _localStorage = localStorage; _http = http; } public override async Task GetAuthenticationStateAsync() { string userDetailsStr = await _localStorage.GetFromSecureStorageAsync(nameof(Setting.UserBasicDetails)); AuthenticationState state = null; if (!string.IsNullOrEmpty(userDetailsStr)) { var userBasicDetail = JsonConvert.DeserializeObject(userDetailsStr); //var handler = new JwtSecurityTokenHandler(); //var jsontoken = handler.ReadToken(userBasicDetail?.AccessToken) as JwtSecurityToken; var token = userBasicDetail?.AccessToken; var identity = new ClaimsIdentity(); _http.DefaultRequestHeaders.Authorization = null; if (!string.IsNullOrEmpty(token)) { identity = new ClaimsIdentity(ParseClaimsFromJwt(token), "jwt"); _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Replace("\"", "")); } var user = new ClaimsPrincipal(identity); state = new AuthenticationState(user); NotifyAuthenticationStateChanged(Task.FromResult(state)); } else { state = new AuthenticationState(new ClaimsPrincipal()); } return state; } public static IEnumerable ParseClaimsFromJwt(string jwt) { var payload = jwt.Split('.')[1]; var jsonBytes = ParseBase64WithoutPadding(payload); var keyValuePairs = System.Text.Json.JsonSerializer.Deserialize>(jsonBytes); return keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString())); } private static byte[] ParseBase64WithoutPadding(string base64) { switch (base64.Length % 4) { case 2: base64 += "=="; break; case 3: base64 += "="; break; } return Convert.FromBase64String(base64); } } }