using System.Text.Json; namespace SharepointToolbox.Web.Services.Auth; public class TokenRefreshService : ITokenRefreshService { private readonly HttpClient _http; public TokenRefreshService(HttpClient http) { _http = http; } public async Task RefreshAsync( string refreshToken, string tenantId, string clientId, string scope) { var body = new Dictionary { ["grant_type"] = "refresh_token", ["client_id"] = clientId, ["refresh_token"] = refreshToken, ["scope"] = scope, }; var url = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token"; var resp = await _http.PostAsync(url, new FormUrlEncodedContent(body)); var json = await resp.Content.ReadAsStringAsync(); if (!resp.IsSuccessStatusCode) throw new InvalidOperationException($"Token refresh failed ({resp.StatusCode}): {json}"); using var doc = JsonDocument.Parse(json); var root = doc.RootElement; var expiresIn = root.GetProperty("expires_in").GetInt32(); return new TokenRefreshResult { AccessToken = root.GetProperty("access_token").GetString()!, RefreshToken = root.TryGetProperty("refresh_token", out var rt) ? rt.GetString()! : refreshToken, ExpiresAt = DateTimeOffset.UtcNow.AddSeconds(expiresIn - 30), }; } }