tuitio/IdentityServer.Wrapper/Services/IdentityService.cs

81 lines
3.1 KiB
C#
Raw Normal View History

2020-12-21 00:45:10 +02:00
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<Token> Authenticate(string userName, string password)
{
var route = string.Format(ApiRoutes.Authentication, userName, password);
var result = await ExecutePostRequest<Token>(route);
return result;
}
public async Task<User> Authorize(string token)
{
var route = string.Format(ApiRoutes.Authorization, token);
var result = await ExecutePostRequest<User>(route);
return result;
}
#region Private methods
private async Task<T> ExecuteGetRequest<T>(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<T>(await response.Content.ReadAsStringAsync());
return result;
}
}
private async Task<R> ExecutePostRequest<R>(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<R>(await response.Content.ReadAsStringAsync());
return result;
}
}
private async Task<R> ExecutePostRequest<R, B>(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<R>(await response.Content.ReadAsStringAsync());
return result;
}
}
#endregion
}
}