using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; namespace Win_in.Sfs.Wms.DataExchange.Authenticaitons; public class TokenService : ITokenService { private readonly IConfiguration _configuration; private readonly AuthenticationOptions _options; public TokenService(IConfiguration configuration, IOptions options) { _configuration = configuration; _options = options.Value; } public async Task GetTokenAsync(string baseUrl) { var options = _options; var token = await GetTokenAsync(baseUrl, options).ConfigureAwait(false); return token; } public async Task GetTokenAsync(string baseUrl, string username, string password) { var options = new AuthenticationOptions() { client_id = _options.client_id, client_secret = _options.client_secret, grant_type = "password", username = username, password = password }; var token = await GetTokenAsync(baseUrl, options).ConfigureAwait(false); return token; } private static async Task GetTokenAsync(string baseUrl, AuthenticationOptions options) { const string routeString = "connect/token"; var client = new HttpClient(); client.BaseAddress = new Uri(baseUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var content = new FormUrlEncodedContent(new[] { new KeyValuePair("client_id",options.client_id), new KeyValuePair("client_secret",options.client_secret), new KeyValuePair("grant_type",options.grant_type), new KeyValuePair("username",options.username), new KeyValuePair("password",options.password), }); var response = await client.PostAsync(routeString, content).ConfigureAwait(false); response.EnsureSuccessStatusCode(); var dto = await response.Content.ReadFromJsonAsync().ConfigureAwait(false); return dto; } }