using System.Net; using System.Net.Http.Json; using System.Security.Claims; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.Extensions.Logging; using Moonlight.Shared.Http.Responses.Admin.Auth; namespace Moonlight.Frontend.Services; public class RemoteAuthProvider : AuthenticationStateProvider { private readonly ILogger Logger; private readonly HttpClient HttpClient; public RemoteAuthProvider(ILogger logger, HttpClient httpClient) { Logger = logger; HttpClient = httpClient; } public override async Task GetAuthenticationStateAsync() { try { var claimResponses = await HttpClient.GetFromJsonAsync( "api/auth/claims", Constants.SerializerOptions ); var claims = claimResponses!.Select(claim => new Claim(claim.Type, claim.Value)); return new AuthenticationState( new ClaimsPrincipal(new ClaimsIdentity(claims, "remote")) ); } catch (HttpRequestException e) { if (e.StatusCode != HttpStatusCode.Unauthorized) Logger.LogError(e, "An api error occured while requesting claims from api"); } catch (Exception e) { Logger.LogError(e, "An unhandled error occured while requesting claims from api"); } return new AuthenticationState(new ClaimsPrincipal()); } }