Finished enqueue site
This commit is contained in:
46
SpotiParty.Web/Services/AuthorizationHandler.cs
Normal file
46
SpotiParty.Web/Services/AuthorizationHandler.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
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<SpotifyClient> 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<string, string>("grant_type", "client_credentials")
|
||||
}));
|
||||
response.EnsureSuccessStatusCode();
|
||||
_token = await response.Content.ReadFromJsonAsync<AuthResponse>();
|
||||
|
||||
if (_token is null) throw new AuthenticationException("Spotify auth failed!");
|
||||
}
|
||||
|
||||
return new SpotifyClient(_token.AccessToken, _token.TokenType);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user