dotnet / dotnet/yarp

Add a way to create custom CookieOptions for CookieSessionAffinityPolicy

Open
#1,696 4 comments 1 reaction 0 assignees View on GitHub
Type: Idea
Dominant language
C#
Stars
9.6k
Forks
933
Avg merge
12d 18h
Merged PRs (30d)
2

Description

### What should we add or change to make your life better?

For example add a `SessionAffinityCookieConfig.CookieBuilder` property which, if not `null`, is used instead of [existing code in `SetAffinityKey`](https://github.com/microsoft/reverse-proxy/blob/a07262b008ab1461d953fe979ec54e2cc88263e0/src/ReverseProxy/SessionAffinity/CookieSessionAffinityPolicy.cs#L42-L52) to create custom `CookieOptions`.

```c#
public sealed partial record SessionAffinityCookieConfig
{
public Func? CookieBuilder { get; init; }
}
```

### Why is this important to you?

I have a usecase where one cluster serves content for multiple domains and subdomains and I need a way to specify the session affinity cookie domain dynamically so that the session affinity cookie is the same for all subdomains to provide a better user experience. (A user can use the same session on the same server for all subdomains.)

For example the cluster serves the four domains:
- a.test1.com
- b.test1.com
- a.test2.com
- b.test2.com

For the domains "a.test1.com" and "b.test1.com" the session affinity cookie domain should be `*.test1.com`.
For the domains "a.test2.com" and "b.test2.com" the session affinity cookie domain should be `*.test2.com`.

Since I configure the cluster in code I could provide a custom `CookieBuilder` which could set the cookie domain dynamically. Which would be similar to the [`Microsoft.AspNetCore.Http.CookieBuilder.Build`](https://github.com/dotnet/aspnetcore/blob/69842442f8524908972aedef2e2cb00a93b923fb/src/Http/Http.Abstractions/src/CookieBuilder.cs#L93) method in aspnet core.

Demo usage:
```c#
var cookieConfig = new SessionAffinityCookieConfig
{
CookieBuilder = (config, cluster, context) =>
{
var cookieOptions = new CookieOptions();
// ...
var parts = context.Request.Host.Host.Split('.');
if (parts.Length > 2)
{
parts = parts[^2..];
}
cookieOptions.Domain = string.Join('.', parts);
return cookieOptions;
}
};
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.