Skip to content

Commit

Permalink
Merge branch 'main' into beh/persistent-cookies-server-side-sessions-bug
Browse files Browse the repository at this point in the history
  • Loading branch information
bhazen authored Feb 4, 2025
2 parents ab1387a + 0fe5539 commit 4f57e0c
Show file tree
Hide file tree
Showing 57 changed files with 665 additions and 577 deletions.
101 changes: 101 additions & 0 deletions bff/docs/upgrade-guide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Upgrade guide

## From v2.x => v3.x

If you rely on the default extension methods for wiring up the BFF, then V3 should be a drop-in replacement.

### Migrating from custom implementations of IHttpMessageInvokerFactory

In Duende.BFF V2, there was an interface called IHttpMessageInvokerFactory. This class was responsible for creating
and wiring up yarp's HttpMessageInvoker. This interface has been removed in favor yarp's IForwarderHttpClientFactory.

One common scenario for creating a custom implementation of this class was for mocking the http client
during unit testing.

If you wish to inject a http handler for unit testing, you should now inject a custom IForwarderHttpClientFactory. For example:

``` c#
// A Forwarder factory that forwards the messages to a message handler (which can be easily retrieved from a testhost)
public class BackChannelHttpMessageInvokerFactory(HttpMessageHandler backChannel)
: IForwarderHttpClientFactory
{
public HttpMessageInvoker CreateClient(ForwarderHttpClientContext context) =>
new HttpMessageInvoker(backChannel);
}

// Wire up the forwarder in your application's test host:
services.AddSingleton<IForwarderHttpClientFactory>(
new BackChannelHttpMessageInvokerFactory(_apiHost.Server.CreateHandler()));


```

### Migrating from custom implementations IHttpTransformerFactory
The *IHttpTransformerFactory* was a way to globally configure the YARP tranform pipeline. In V3, the way that
the default *endpoints.MapRemoteBffApiEndpoint()* method builds up the YARP transform has been simplified
significantly. Most of the logic has been pushed down to the *AccessTokenRequestTransform*.

Here are common scenario's for implementing your own *IHttpTransformerFactory* and how to upgrade:

**Replacing defaults**

If you used a custom implementation of IHttpTransformerFactory to change the default behavior of *MapRemoteBffApiEndpoint()*,
for example to add additional transforms, then you can now inject a custom delegate into the di container:

```
services.AddSingleton<BffYarpTransformBuilder>(CustomDefaultYarpTransforms);
//...
// This is an example of how to add a response header to ALL invocations of MapRemoteBffApiEndpoint()
private void CustomDefaultBffTransformBuilder(string localpath, TransformBuilderContext context)
{
context.AddResponseHeader("added-by-custom-default-transform", "some-value");
DefaultBffYarpTransformerBuilders.DirectProxyWithAccessToken(localpath, context);
}
```

Another way of doing this is to create a custom extensionmethod *MyCustomMapRemoteBffApiEndpoint()* that wraps
the MapRemoteBffApiEndpoint() and use that everywhere in your application. This is a great way to add other defaults
that should apply to all endpoints, such as requiring a specific type of access token.

**Configuring transforms for a single route**
Another common usecase for overriding the IHttpTransformerFactory was to have a custom transform for a single route, by
applying a switch statement and testing for specific routes.

Now, there is an overload on the *endpoints.MapRemoteBffApiEndpoint()* that allows you to configure the pipeline directly:

``` c#

endpoints.MapRemoteBffApiEndpoint(
"/local-path",
_apiHost.Url(),
context =>
{
// do something custom: IE: copy request headers
context.CopyRequestHeaders = true;

// wire up the default transformer logic
DefaultTransformers.DirectProxyWithAccessToken("/local-path", context);
})
// Continue with normal BFF configuration, for example, allowing optional user access tokens
.WithOptionalUserAccessToken();

```

### Removed method RemoteApiEndpoint.Map(localpath, apiAddress).
The Map method was no longer needed as most of the logic had been moved to either the MapRemoteBffApiEndpoint and the DefaultTransformers. The map method also wasn't very explicit about what it did and a number of test scenario's tried to verify if it wasn't called wrongly. You are now expected to call the method MapRemoteBffApiEndpoint. This method now has a nullable parameter that allows you to inject your own transformers.

### AccessTokenRetrievalContext properties are now typed
The LocalPath and ApiAddress properties are now typed. They used to be strings. If you rely on these, for example for implementing
a custom IAccessTokenRetriever, then you should adjust their usage accordingly.

/// <summary>
/// The locally requested path.
/// </summary>
public required PathString LocalPath { get; set; }

/// <summary>
/// The remote address of the API.
/// </summary>
public required Uri ApiAddress { get; set; }
3 changes: 3 additions & 0 deletions bff/migrations/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
</PropertyGroup>
<Import Project="../../samples.props" />
</Project>
4 changes: 2 additions & 2 deletions bff/migrations/UserSessionDb/UserSessionDb.csproj
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFrameworks>net9.0</TargetFrameworks>
<TargetFramework>net9.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" >
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
2 changes: 1 addition & 1 deletion bff/samples/Apis/Api.DPoP/Api.DPoP.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFrameworks>net9.0</TargetFrameworks>
</PropertyGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion bff/samples/Bff/Bff.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFrameworks>net9.0</TargetFrameworks>
<RootNamespace>Bff</RootNamespace>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand Down
19 changes: 19 additions & 0 deletions bff/samples/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,4 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<!-- This line is needed because:
Aspire needs a single target framework
(until this is resolved: https://github.com/dotnet/aspire/issues/2962)
When you add <TargetFrameworks>net9.0</TargetFrameworks> then aspire thinks there are more than
one framework. But this causes a problem for the Directory.Packages.props file.
In the Directory.Packages.props where we check for $(TargetFramework) == 'net9.0',
which is ONLY set if you use <TargetFrameworks>net9.0</TargetFrameworks> in the csproj file, not
if you set <TargetFramework>.
Now normally it's not recommended to set both, however, since this is only for samples, AND
we do need this check, we're setting it here as well.
-->
<TargetFramework>net9.0</TargetFramework>
</PropertyGroup>
<Import Project="../../samples.props" />
</Project>
2 changes: 1 addition & 1 deletion bff/samples/Hosts.Tests/Hosts.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFrameworks>net9.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
Expand Down
4 changes: 2 additions & 2 deletions bff/samples/Hosts.Tests/TestInfra/BffClient.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// // Copyright (c) Duende Software. All rights reserved.
// // See LICENSE in the project root for license information.
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.

using System.Text.Json;
using AngleSharp;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// // Copyright (c) Duende Software. All rights reserved.
// // See LICENSE in the project root for license information.
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.

namespace Hosts.Tests.TestInfra;

Expand Down
4 changes: 2 additions & 2 deletions bff/samples/IdentityServer/Extensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// // Copyright (c) Duende Software. All rights reserved.
// // See LICENSE in the project root for license information.
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.

using IdentityServerHost;
namespace IdentityServer;
Expand Down
4 changes: 2 additions & 2 deletions bff/samples/IdentityServer/ServiceDiscoveringClientStore.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// // Copyright (c) Duende Software. All rights reserved.
// // See LICENSE in the project root for license information.
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.

using Duende.IdentityModel;
using Duende.IdentityServer.Models;
Expand Down
41 changes: 41 additions & 0 deletions bff/src/Duende.Bff.Blazor.Client/ClaimRecord.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.Text.Json.Serialization;

namespace Duende.Bff;

/// <summary>
/// Serialization friendly claim.
///
/// Note, this is a copy of the ClaimRecord class from Duende.Bff, but since we can't create a reference to it, we need to copy it here.
/// We also can't link to it (as we do with the extensions) because the other ClaimRecord class is public and this one is intentionally internal.
/// </summary>
internal class ClaimRecord()
{
/// <summary>
/// Serialization friendly claim
/// </summary>
/// <param name="type">The type</param>
/// <param name="value">The Value</param>
internal ClaimRecord(string type, object value) : this()
{
Type = type;
Value = value;
}

/// <summary>
/// The type
/// </summary>
[JsonPropertyName("type")]
public string Type { get; init; } = default!;

/// <summary>
/// The value
/// </summary>
[JsonPropertyName("value")]
public object Value { get; init; } = default!;

/// <summary>
/// The value type
/// </summary>
[JsonPropertyName("valueType")]
public string? ValueType { get; init; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
<TargetFrameworks>net8.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>

<ItemGroup>
<Compile Include="..\Duende.Bff\Shared\ClaimLite.cs" Link="Shared\ClaimLite.cs" />
<Compile Include="..\Duende.Bff\Shared\ClaimsLiteExtensions.cs" Link="Shared\ClaimsLiteExtensions.cs" />
<Compile Include="..\Duende.Bff\Shared\ClaimsPrincipalLite.cs" Link="Shared\ClaimsPrincipalLite.cs" />
<Compile Include="..\Duende.Bff\Shared\ClaimRecordExtensions.cs" Link="Shared\ClaimRecordExtensions.cs" />
<Compile Include="..\Duende.Bff\Shared\ClaimsPrincipalRecord.cs" Link="Shared\ClaimsPrincipalRecord.cs" />
</ItemGroup>

<ItemGroup>
Expand Down
3 changes: 0 additions & 3 deletions bff/src/Duende.Bff.Blazor.Client/Internals/GetUserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,6 @@ public async ValueTask<ClaimsPrincipal> GetUserAsync(bool useCache = true)
return _cachedUser;
}

// TODO - Consider using ClaimLite instead here
record ClaimRecord(string Type, object Value);

internal async Task<ClaimsPrincipal> FetchUser()
{
try
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ internal class PersistentUserService(PersistentComponentState state, ILogger<Per
/// <inheritdoc />
public ClaimsPrincipal GetPersistedUser()
{
if (!state.TryTakeFromJson<ClaimsPrincipalLite>(nameof(ClaimsPrincipalLite), out var lite) || lite is null)
if (!state.TryTakeFromJson<ClaimsPrincipalRecord>(nameof(ClaimsPrincipalRecord), out var lite) || lite is null)
{
logger.LogDebug("Failed to load persisted user.");
return new ClaimsPrincipal(new ClaimsIdentity());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,14 @@ private async Task OnPersistingAsync()
var authenticationState = await _authenticationStateTask;

var claims = authenticationState.User.Claims
.Select(c => new ClaimLite
.Select(c => new ClaimRecord
{
Type = c.Type,
Value = c.Value?.ToString() ?? string.Empty,
ValueType = c.ValueType == ClaimValueTypes.String ? null : c.ValueType
}).ToArray();

var principal = new ClaimsPrincipalLite
var principal = new ClaimsPrincipalRecord
{
AuthenticationType = authenticationState.User.Identity!.AuthenticationType,
NameClaimType = authenticationState.User.Identities.First().NameClaimType,
Expand All @@ -90,7 +90,7 @@ private async Task OnPersistingAsync()

_logger.LogDebug("Persisting Authentication State");

_state.PersistAsJson(nameof(ClaimsPrincipalLite), principal);
_state.PersistAsJson(nameof(ClaimsPrincipalRecord), principal);
}


Expand Down
4 changes: 3 additions & 1 deletion bff/src/Duende.Bff.Blazor/Duende.Bff.Blazor.csproj
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>

</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
Expand Down
Loading

0 comments on commit 4f57e0c

Please sign in to comment.