using IdentityServer.PublishedLanguage.Dto; using IdentityServer.Wrapper.Constants; using IdentityServer.Wrapper.Models; using Newtonsoft.Json; using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace IdentityServer.Wrapper.Services { internal class IdentityService : IIdentityService { private const string _contentType = "application/json"; private readonly HttpClient _httpClient; public IdentityService(HttpClient httpClient, ServiceConfiguration configuration) { httpClient.BaseAddress = new Uri(configuration.BaseAddress); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_contentType)); _httpClient = httpClient; } public async Task Authenticate(string userName, string password) { var route = string.Format(ApiRoutes.Authentication, userName, password); var result = await ExecutePostRequest(route); return result; } public async Task Authorize(string token) { var route = string.Format(ApiRoutes.Authorization, token); var result = await ExecutePostRequest(route); return result; } #region Private methods private async Task ExecuteGetRequest(string route) where T : class { using (var response = await _httpClient.GetAsync(route)) { if (!response.IsSuccessStatusCode) throw new Exception($"Error: StatusCode: {response.StatusCode}; Reason: {response.ReasonPhrase}"); var result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); return result; } } private async Task ExecutePostRequest(string route) where R : class { HttpContent content = new StringContent(JsonConvert.SerializeObject(string.Empty), Encoding.UTF8, _contentType); using (var response = await _httpClient.PostAsync(route, content)) { if (!response.IsSuccessStatusCode) throw new Exception($"Error: StatusCode: {response.StatusCode}; Reason: {response.ReasonPhrase}"); var result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); return result; } } private async Task ExecutePostRequest(string route, B body) where R : class where B : class { HttpContent content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, _contentType); using (var response = await _httpClient.PostAsync(route, content)) { if (!response.IsSuccessStatusCode) throw new Exception($"Error: StatusCode: {response.StatusCode}; Reason: {response.ReasonPhrase}"); var result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); return result; } } #endregion } }