Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Epic aot #352

Merged
merged 2 commits into from
Feb 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions LibraryCore.sln
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibraryCore.Aot.Json", "Src
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Aot", "Aot", "{896C5DB1-3EDC-4DCC-AAAB-73F705B52B18}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibraryCore.Tests.Aot.Json", "Tests\LibraryCore.Tests.Aot.Json\LibraryCore.Tests.Aot.Json.csproj", "{01CB3A66-9110-4BFA-9D7D-3117578E1575}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -288,6 +290,10 @@ Global
{9169F37A-8A3E-4E73-A75E-830A3F8E3224}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9169F37A-8A3E-4E73-A75E-830A3F8E3224}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9169F37A-8A3E-4E73-A75E-830A3F8E3224}.Release|Any CPU.Build.0 = Release|Any CPU
{01CB3A66-9110-4BFA-9D7D-3117578E1575}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{01CB3A66-9110-4BFA-9D7D-3117578E1575}.Debug|Any CPU.Build.0 = Debug|Any CPU
{01CB3A66-9110-4BFA-9D7D-3117578E1575}.Release|Any CPU.ActiveCfg = Release|Any CPU
{01CB3A66-9110-4BFA-9D7D-3117578E1575}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -347,6 +353,7 @@ Global
{43270FFA-B5A6-4F20-AE0B-C7C3F9DBD957} = {EC8F3521-E377-420D-B5A1-82D2B29FB611}
{9169F37A-8A3E-4E73-A75E-830A3F8E3224} = {896C5DB1-3EDC-4DCC-AAAB-73F705B52B18}
{896C5DB1-3EDC-4DCC-AAAB-73F705B52B18} = {75C64940-5413-442D-B876-AEAA8DC20FC0}
{01CB3A66-9110-4BFA-9D7D-3117578E1575} = {896C5DB1-3EDC-4DCC-AAAB-73F705B52B18}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E61C7767-7D12-4313-8DA2-56AE8FC5AAD5}
Expand Down
2 changes: 1 addition & 1 deletion Src/LibraryCore.ApiClient/LibraryCore.ApiClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<Description>Simplified library to make api calls using http client</Description>
<RepositoryUrl>https://github.com/dibiancoj/LibraryCore</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<Version>9.1.0</Version>
<Version>9.2.0</Version>
<Title>LibraryCore - Api Client</Title>
<IsTrimmable>true</IsTrimmable>
<IsAotCompatible Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))">true</IsAotCompatible>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using LibraryCore.ApiClient;
using LibraryCore.Aot.Json;
using LibraryCore.ApiClient;
using LibraryCore.ApiClient.ExtensionMethods;
using LibraryCore.Shared;
using Microsoft.IdentityModel.Tokens;
Expand All @@ -8,6 +9,7 @@
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;

namespace LibraryCore.Healthcare.Epic.Authentication;

Expand All @@ -26,13 +28,23 @@ public static async Task<EpicClientCredentialsAuthorizationToken> TokenAsync(Htt
string tokenEndPointUrl,
string clientAssertion,
CancellationToken cancellationToken = default)
{
return await TokenAsync(httpClient, tokenEndPointUrl, clientAssertion, ResolveJsonType.ResolveJsonTypeInfo<EpicClientCredentialsAuthorizationToken>(), cancellationToken);
}

public static async Task<EpicClientCredentialsAuthorizationToken> TokenAsync(HttpClient httpClient,
string tokenEndPointUrl,
string clientAssertion,
JsonTypeInfo<EpicClientCredentialsAuthorizationToken> jsonTypeInfo,
CancellationToken cancellationToken = default)
{
var request = new FluentRequest(HttpMethod.Post, tokenEndPointUrl)
.AddFormsUrlEncodedBody(new("grant_type", "client_credentials"),
new("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
new("client_assertion", clientAssertion));
.AddFormsUrlEncodedBody(new("grant_type", "client_credentials"),
new("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
new("client_assertion", clientAssertion));

return await httpClient.SendRequestToJsonAsync(request, jsonTypeInfo, cancellationToken: cancellationToken) ?? throw new Exception("Can't Deserialize Token");

return await httpClient.SendRequestToJsonAsync<EpicClientCredentialsAuthorizationToken>(request, cancellationToken: cancellationToken) ?? throw new Exception("Can't Deserialize Token");
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using LibraryCore.Shared;
using Microsoft.Extensions.Caching.Memory;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization.Metadata;

namespace LibraryCore.Healthcare.Fhir.MessageHandlers.AuthenticationHandler.TokenBearerProviders.Implementations;

Expand All @@ -14,8 +15,18 @@ public class EpicClientCredentialsBearerTokenProvider(IMemoryCache memoryCache,
HttpClient httpClient,
string tokenEndPointUrl,
string rawPrivateKeyContentInPemFile,
string clientId) : IFhirBearerTokenProvider
string clientId,
JsonTypeInfo<EpicClientCredentialsAuthorizationToken> jsonTypeInfo) : IFhirBearerTokenProvider
{
public EpicClientCredentialsBearerTokenProvider(IMemoryCache memoryCache,
HttpClient httpClient,
string tokenEndPointUrl,
string rawPrivateKeyContentInPemFile,
string clientId)
: this(memoryCache, httpClient, tokenEndPointUrl, rawPrivateKeyContentInPemFile, clientId, Aot.Json.ResolveJsonType.ResolveJsonTypeInfo<EpicClientCredentialsAuthorizationToken>())
{
}

private static TimeSpan CacheBufferTimePeriod { get; } = new TimeSpan(0, 1, 0);

public async ValueTask<string> AccessTokenAsync(CancellationToken cancellationToken = default)
Expand All @@ -24,7 +35,7 @@ public async ValueTask<string> AccessTokenAsync(CancellationToken cancellationTo
{
var clientAssertion = ClientCredentialsAuthentication.CreateEpicClientAssertionJwtToken(rawPrivateKeyContentInPemFile, clientId, tokenEndPointUrl);

var tokenResult = await ClientCredentialsAuthentication.TokenAsync(httpClient, tokenEndPointUrl, clientAssertion, cancellationToken);
var tokenResult = await ClientCredentialsAuthentication.TokenAsync(httpClient, tokenEndPointUrl, clientAssertion, jsonTypeInfo, cancellationToken);

//giving it a minute buffer so we don't get too close to the expiration
var buffer = tokenResult.ExpiresIn <= CacheBufferTimePeriod.TotalSeconds ?
Expand Down
10 changes: 7 additions & 3 deletions Src/LibraryCore.Healthcare/LibraryCore.Healthcare.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<Description>.NetCore Common Utilities For Healthcare</Description>
<RepositoryUrl>https://github.com/dibiancoj/LibraryCore</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<Version>9.0.2</Version>
<Version>9.1.0</Version>
<Title>LibraryCore - Healthcare</Title>
<IsAotCompatible Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))">false</IsAotCompatible>
<IsTrimmable>true</IsTrimmable>
Expand All @@ -28,10 +28,14 @@

<ItemGroup>
<PackageReference Include="Hl7.Fhir.R4" Version="5.6.1" />
<PackageReference Include="LibraryCore.ApiClient" Version="9.0.1" />
<PackageReference Include="LibraryCore.Caching" Version="9.0.1" />
<PackageReference Include="LibraryCore.ApiClient" Version="9.1.0" />
<PackageReference Include="LibraryCore.Caching" Version="9.0.2" />
<PackageReference Include="LibraryCore.Core" Version="9.0.1" />
<PackageReference Include="System.Text.Json" Version="8.0.2" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\LibraryCore.Shared\LibraryCore.Aot.Json\LibraryCore.Aot.Json.csproj" />
</ItemGroup>

</Project>
1 change: 1 addition & 0 deletions Tests/LibraryCore.Tests.Aot.Json/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using Xunit;
35 changes: 35 additions & 0 deletions Tests/LibraryCore.Tests.Aot.Json/JsonSerializationTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using LibraryCore.Aot.Json;
using System.Text.Json;

namespace LibraryCore.Tests.Aot.Json;

public class JsonSerializationTest
{
public record TestModel(int Id, string Text);

[Fact]
public void NonAotWithGeneral()
{
var serializationOptions = new JsonSerializerOptions(JsonSerializerDefaults.General);

var json = JsonSerializer.Serialize(new TestModel(99, "99"), serializationOptions);

var backToModel = JsonSerializer.Deserialize(json, ResolveJsonType.ResolveJsonTypeInfo<TestModel>())!;

Assert.Equal(99, backToModel.Id);
Assert.Equal("99", backToModel.Text);
}

[Fact]
public void NonAotWithWeb()
{
var serializationOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);

var json = JsonSerializer.Serialize(new TestModel(88, "88"), serializationOptions);

var backToModel = JsonSerializer.Deserialize(json, ResolveJsonType.ResolveJsonTypeInfo<TestModel>())!;

Assert.Equal(88, backToModel.Id);
Assert.Equal("88", backToModel.Text);
}
}
39 changes: 39 additions & 0 deletions Tests/LibraryCore.Tests.Aot.Json/LibraryCore.Tests.Aot.Json.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<Using Include="Xunit" />
<Using Include="Moq" />
</ItemGroup>

<ItemGroup>
<None Remove="coverage.opencover.xml" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="coverlet.msbuild" Version="6.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="xunit" Version="2.7.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.7">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Src\LibraryCore.Shared\LibraryCore.Aot.Json\LibraryCore.Aot.Json.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
using LibraryCore.Healthcare.Epic.Authentication;
using LibraryCore.Shared;
using Moq.Protected;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace LibraryCore.Tests.Healthcare.Epic.Authentication;

[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(EpicClientCredentialsAuthorizationToken))]
internal partial class JsonContext : JsonSerializerContext
{
}

public class ClientCredentialsAuthenticationTest
{
internal const string PrivateKeyTester = """
Expand Down Expand Up @@ -78,6 +86,44 @@ public async Task ClientCredentialsTokenAsync()
Assert.Contains(result.Scopes, x => x == "def");
}

[Trait(ErrorMessages.AotUnitTestTraitName, ErrorMessages.AotUnitTestTraitValue)]
[Fact]
public async Task ClientCredentialsTokenAsync_Aot()
{
const string clientAssertion = "abc";
var mockHttpHandler = new Mock<HttpMessageHandler>();
var httpClient = new HttpClient(mockHttpHandler.Object);

var mockResponse = new HttpResponseMessage
{
StatusCode = System.Net.HttpStatusCode.OK,

Content = new StringContent(JsonSerializer.Serialize(new EpicClientCredentialsAuthorizationToken("Bearer", "Abcdef", "abc def", 90)), Encoding.UTF8, "application/json")
};

mockHttpHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(msg => CheckBodyExpression(msg)),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(mockResponse);

var result = await ClientCredentialsAuthentication.TokenAsync(httpClient, "https://mytokenendpoint", clientAssertion, JsonContext.Default.EpicClientCredentialsAuthorizationToken);

mockHttpHandler
.Protected()
.Verify(
nameof(HttpClient.SendAsync),
Times.Once(),
ItExpr.Is<HttpRequestMessage>(msg => CheckBodyExpression(msg)),
ItExpr.IsAny<CancellationToken>());

Assert.Equal(2, result.Scopes.Count);
Assert.Contains(result.Scopes, x => x == "abc");
Assert.Contains(result.Scopes, x => x == "def");
}

private static bool CheckBodyExpression(HttpRequestMessage msg)
{
const string expectedBody = "grant_type=client_credentials&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&client_assertion=abc";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
using LibraryCore.Healthcare.Epic.Authentication;
using LibraryCore.Healthcare.Fhir.MessageHandlers.AuthenticationHandler.TokenBearerProviders.Implementations;
using LibraryCore.Shared;
using LibraryCore.Tests.Healthcare.Epic.Authentication;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using Moq.Protected;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace LibraryCore.Tests.Healthcare.Fhir.HttpClientHandlers.TokenBearerProviders;

[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(EpicClientCredentialsAuthorizationToken))]
internal partial class JsonContextClientCredentailsTokenProvider : JsonSerializerContext
{
}

public class EpicClientCredentialsBearerTokenProviderTest
{
[Fact]
Expand Down Expand Up @@ -60,4 +68,56 @@ public async Task CachingEpicClientCredsTest()
ItExpr.Is<HttpRequestMessage>(msg => true),
ItExpr.IsAny<CancellationToken>());
}

[Trait(ErrorMessages.AotUnitTestTraitName, ErrorMessages.AotUnitTestTraitValue)]
[Fact]
public async Task CachingEpicClientCredsTest_Aot()
{
var mockHttpHandler = new Mock<HttpMessageHandler>();
var httpClient = new HttpClient(mockHttpHandler.Object);

var mockResponse1 = new HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new StringContent(JsonSerializer.Serialize(new EpicClientCredentialsAuthorizationToken("Bearer", "Abcdef", "abc def", 5)), Encoding.UTF8, "application/json")
};

var mockResponse2 = new HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new StringContent(JsonSerializer.Serialize(new EpicClientCredentialsAuthorizationToken("Bearer", "zzzzzz", "abc def", 5)), Encoding.UTF8, "application/json")
};

mockHttpHandler
.Protected()
.SetupSequence<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(msg => true),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(mockResponse1)
.ReturnsAsync(mockResponse2);

var memoryCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));

var tokenProvider = new EpicClientCredentialsBearerTokenProvider(memoryCache,
httpClient,
"http://www.fhir.token.com",
ClientCredentialsAuthenticationTest.PrivateKeyTester,
"ClientAbc",
JsonContextClientCredentailsTokenProvider.Default.EpicClientCredentialsAuthorizationToken);

Assert.Equal("Abcdef", await tokenProvider.AccessTokenAsync());
Assert.Equal("Abcdef", await tokenProvider.AccessTokenAsync());

await Task.Delay(TimeSpan.FromSeconds(6));

Assert.Equal("zzzzzz", await tokenProvider.AccessTokenAsync());
Assert.Equal("zzzzzz", await tokenProvider.AccessTokenAsync());

mockHttpHandler
.Protected()
.Verify<Task<HttpResponseMessage>>(
"SendAsync",
Times.Exactly(2),
ItExpr.Is<HttpRequestMessage>(msg => true),
ItExpr.IsAny<CancellationToken>());
}
}
Loading