From 0356f5c9dd1c0bf77df7e1f84daeb5dcba039819 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20LAVERGNE?= Date: Sun, 16 Jun 2024 19:10:20 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9E=95=20Class=20for=20requesting=20the=20ac?= =?UTF-8?q?cess=20token=20for=20the=20API=20(read=20&=20return)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/GameAtlas/Models/API/AuthService.cs | 46 +++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Sources/GameAtlas/Models/API/AuthService.cs 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; + } + } +}