//using IdentityProvider.Protos.AuthService; using Grpc.Net.Client; using GrpcShared; using GrpcShared.DTO.Auth; using GrpcShared.Interfaces; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; using Newtonsoft.Json; using System.Net.Http.Headers; using System.Text; using System.Text.Json; namespace IdentityProvider.Services { public class AuthService : IAuthService { private readonly ILogger _logger; private readonly CodeRequest _params; private readonly IHttpClientFactory _httpClientFactory; public AuthService(ILogger logger, IOptions options, IHttpClientFactory httpClientFactory) { _logger = logger; _params = options.Value; _httpClientFactory = httpClientFactory; } public async Task GetAccessToken(TokenRequest tokenRequest) { var http = _httpClientFactory.CreateClient(); string url = "https://accounts.spotify.com/api/token"; http.BaseAddress = new Uri(url); //get client id and secret from appsettings, convert to base64 and set as header var secrets = await GetAuthParams(); byte[] contentType = Encoding.UTF8.GetBytes($"{secrets.ClientId}:{secrets.ClientSecret}"); http.DefaultRequestHeaders.Add(HeaderNames.Authorization, "Basic " + Convert.ToBase64String(contentType)); //ACCEPT HEADER http.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); //BODY var requestBody = new Dictionary(); requestBody["grant_type"] = tokenRequest.grant_type; requestBody["code"] = tokenRequest.code!; requestBody["redirect_uri"] = secrets.RedirectURI!; var response = await http.PostAsync(url, new FormUrlEncodedContent(requestBody)); var contents = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); return await Task.FromResult(new TokenResponse { AccessToken = contents!.AccessToken, RefreshToken = contents!.RefreshToken, ExpiresIn = contents!.ExpiresIn }); } public async Task GetAuthParams() { var authParams = new CodeRequest { ClientId = _params.ClientId, RedirectURI = _params.RedirectURI, Scope = _params.Scope, ClientSecret = _params.ClientSecret }; return await Task.FromResult(authParams); } } }