diff --git a/Sources/GameAtlas/Models/API/AuthService.cs b/Sources/GameAtlas/Models/API/AuthService.cs new file mode 100644 index 0000000..10eb191 --- /dev/null +++ b/Sources/GameAtlas/Models/API/AuthService.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using Microsoft.Extensions.Options; +using System.Threading.Tasks; + +namespace Models.API +{ + public class AuthService + { + private readonly HttpClient _httpClient; + + public AuthService(HttpClient httpClient) + { + _httpClient = httpClient; + } + + public async Task GetAccessTokenAsync(string clientId, string clientSecret) + { + var request = new HttpRequestMessage(HttpMethod.Post, "https://id.twitch.tv/oauth2/token"); + request.Content = new FormUrlEncodedContent(new[] + { + new KeyValuePair("client_id", clientId), + new KeyValuePair("client_secret", clientSecret), + new KeyValuePair("grant_type", "client_credentials") + }); + + var response = await _httpClient.SendAsync(request); + + if (!response.IsSuccessStatusCode) + { + var errorContent = await response.Content.ReadAsStringAsync(); + Console.WriteLine($"Request error: {response.StatusCode}, Content: {errorContent}"); + throw new HttpRequestException($"Response status code does not indicate success: {response.StatusCode} ({errorContent})"); + } + + var responseContent = await response.Content.ReadAsStringAsync(); + var oauthResponse = JsonSerializer.Deserialize(responseContent); + return oauthResponse; + } + } +}