system-praktyk-api/src/InternshipSystem.Api/Controllers/GutCasClient.cs
maxchil 54dfcaa7e7 feat/authorization (#39)
move client

merge

add Gut authentication and authorization

merge

dummy

Co-authored-by: MaxchilKH <m.w.bohdanowicz@gmail.com>
2020-09-13 01:07:40 +02:00

75 lines
2.7 KiB
C#

using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using InternshipSystem.Api.Options;
using Microsoft.Extensions.Options;
namespace InternshipSystem.Api.Controllers
{
public class GutCasClient
{
private readonly HttpClient _client;
private readonly SecurityOptions _securityOptions;
public GutCasClient(HttpClient client, IOptions<SecurityOptions> options)
{
_securityOptions = options.Value;
client.BaseAddress = _securityOptions.BaseUrl;
_client = client;
}
public async Task<string> GetCasTokenAsync(string code, CancellationToken cancellationToken)
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "grant_type", "authorization_code" },
{ "client_id", _securityOptions.ClientId },
{ "client_secret", _securityOptions.Secret },
{ "redirect_uri", _securityOptions.RedirectUrl.ToString() },
{ "code", code }
}),
RequestUri = _securityOptions.TokenPath
};
var response = await _client.SendAsync(request, cancellationToken);
await using var stream = await response.Content.ReadAsStreamAsync();
var value = await JsonSerializer.DeserializeAsync<Dictionary<string, object>>(stream);
return value["access_token"].ToString();
}
public async Task<CasUserData> GetProfileAsync(string token, CancellationToken cancellationToken)
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
Content = new StringContent(string.Empty),
RequestUri = _securityOptions.ProfilePath
};
request.Headers.Authorization = AuthenticationHeaderValue.Parse($"Bearer {token}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await _client.SendAsync(request, cancellationToken);
await using var stream = await response.Content.ReadAsStreamAsync();
var result = await JsonSerializer.DeserializeAsync<CasUserProfile>(
stream,
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return result.Attributes;
}
}
}