Yarp Request Transforms using Claims.
install ClaimsTransforms.Yarp from NuGet:
dotnet add package ClaimsTransforms.Yarp
Add Claims Transforms to Yarp services
builder.Services.AddReverseProxy()
.AddClaimsTransforms();
Will append first value of claim type parameter to the end of the route.
Code:
new RouteConfig
{
AuthorizationPolicy = "default",
RouteId = "Route1",
ClusterId = "Cluster1",
Match = new RouteMatch
{
Path = "/profiles/me"
}
}
.WithTransformPathSet("/users")
.WithTransformAppendClaim(ClaimTypes.NameIdentifier)
If ClaimsPrincipal contains
new Claim[] { new ("user-id", "1234") }
RouteConfig code matches /profiles/me and transforms to /users/1234
Config:
"Routes": {
"SampleRoute1": {
"AuthorizationPolicy": "default",
"Match": {
"Path": "/account"
},
"Transforms": [
{ "AppendClaim": "user-id" }
]
}
}
RouteConfig code matches /account and transforms to /account/1234
Will include prefix to routes based on claims pattern. Claims pattern will replace values between { and } with Claim value.
Claims Prefix Pattern example:
/route/{claim-type}
Code:
new RouteConfig
{
AuthorizationPolicy = "default",
Match = new RouteMatch
{
Path = "/assets/{**catchall}"
}
}
.WithTransformClaimsPrefix($"/tenants/{{tenant-id}}/users/{{{ClaimTypes.NameIdentifier}}}")
Config:
"Routes": {
"SampleRoute2": {
"AuthorizationPolicy": "default",
"Match": {
"Path": "/assets/{**catchall}"
},
"Transforms": [
{ "ClaimsPrefix": "/tenants/{tenant-id}/users/{user-id}" }
]
}
}
Example:
Step | Value |
---|---|
Route definition | /assets/{**catchall} |
Request path | /assets/action |
Claims Prefix Pattern | /tenants/{tenant-id}/users/{user-id} |
Claims Principal | new Claim[] { new ("user-id", "1234"), new ("tenant-id", "abc") } |
Result | /tenants/abc/users/1234/assets/action |