Initial commit
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
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<TokenRefreshResult> RefreshAsync(
|
||||
string refreshToken, string tenantId, string clientId, string scope)
|
||||
{
|
||||
var body = new Dictionary<string, string>
|
||||
{
|
||||
["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),
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user