using System.Net.Http.Headers; using System.Security.Authentication; using System.Text; using System.Text.Json.Serialization; using SpotifyAPI.Web; namespace SpotiParty.Web.Services; public sealed class AuthorizationHandler { private AuthResponse? _token; private class AuthResponse { [JsonPropertyName("access_token")] public string AccessToken { get; set; } [JsonPropertyName("token_type")] public string TokenType { get; set; } [JsonPropertyName("expires_in")] public int ExpiresIn { get; set; } } public async Task ConfigureClient() { if (_token is null) { var fileLines = await File.ReadAllLinesAsync(Path.Combine(Environment.CurrentDirectory, ".dev-token")); var clientId = fileLines[0]; var clientSecret = fileLines[1]; var basicAuthToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}")); var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse($"Basic {basicAuthToken}"); var response = await httpClient.PostAsync("https://accounts.spotify.com/api/token", new FormUrlEncodedContent(new[] { new KeyValuePair("grant_type", "client_credentials") })); response.EnsureSuccessStatusCode(); _token = await response.Content.ReadFromJsonAsync(); if (_token is null) throw new AuthenticationException("Spotify auth failed!"); } return new SpotifyClient(_token.AccessToken, _token.TokenType); } }