TourIAm/TIAMWebApp/Shared/Services/CustomAuthStateProvider.cs

76 lines
2.8 KiB
C#

using AyCode.Interfaces.StorageHandlers;
using Microsoft.AspNetCore.Components.Authorization;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Security.Claims;
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<AuthenticationState> GetAuthenticationStateAsync()
{
string userDetailsStr = await _localStorage.GetFromSecureStorageAsync(nameof(Setting.UserBasicDetails));
AuthenticationState state = null;
if (!string.IsNullOrEmpty(userDetailsStr))
{
var userBasicDetail = JsonConvert.DeserializeObject<UserBasicDetails>(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());
NotifyAuthenticationStateChanged(Task.FromResult(state));
}
return state;
}
public static IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
{
var payload = jwt.Split('.')[1];
var jsonBytes = ParseBase64WithoutPadding(payload);
var keyValuePairs = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(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);
}
}
}