yavsc/src/Yavsc.Org.Tests/TestUserMiddleware.cs
Paul Schneider afd02ab5aa test(client): refactor InjectTestUser as a real IMiddleware
Move the X-Test-Role-to-User promotion out of an inline
RequestDelegate and into a proper IMiddleware implementation,
wired through IStartupFilter so it lands after the production
UseAuthentication/UseAuthorization in the request pipeline.

The previous app.Use(...) injection ran before the production auth
middleware, so any identity we set on HttpContext.User was being
overwritten by the next middleware. Wrapping the production
pipeline in TestUserStartupFilter.Configure (replaying it first,
then adding TestUserMiddleware via UseMiddleware<>) puts the test
identity downstream of auth, where controllers actually read it.

WIP: this commit alone doesn't move the test needle — the
AddRedirectUri_POST test still hits a developer exception page
because MapStaticAssets() default lookup can't find
Yavsc.Org.Tests.staticwebassets.endpoints.json in the test bin.
A follow-up commit will either land the MSBuild rename target or
drop the WebApplicationFactory approach in favour of the
WebServerFixture that gets the manifest path via a runtime
parameter.
2026-06-21 21:24:44 +01:00

46 lines
1.7 KiB
C#

using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace Yavsc.Org.Tests;
/// <summary>
/// Middleware that promotes the <c>X-Test-Role</c> request header to
/// an authenticated <see cref="ClaimsPrincipal"/> on
/// <see cref="HttpContext.User"/>. Lets downstream code (controllers,
/// services) call <c>User.GetUserId()</c> and other claim-based
/// helpers as if a real login had happened, while
/// <see cref="TestAuthPolicyProvider"/> independently short-circuits
/// <c>[Authorize(...)]</c> policy checks.
///
/// This middleware is added to the pipeline by
/// <see cref="TestUserStartupFilter"/> so it runs after the
/// production authentication middleware; setting User before
/// <c>UseAuthentication</c> would have it overwritten on the next
/// middleware.
/// </summary>
public class TestUserMiddleware : IMiddleware
{
public const string UserId = "test-user";
public Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var role = context.Request.Headers[TestAuthPolicyProvider.HeaderName].ToString();
if (!string.IsNullOrEmpty(role) &&
(context.User.Identity is null || !context.User.Identity.IsAuthenticated))
{
var identity = new ClaimsIdentity(
new[]
{
new Claim(
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
role),
new Claim(ClaimTypes.NameIdentifier, UserId),
},
authenticationType: "TestAuth");
context.User = new ClaimsPrincipal(identity);
}
return next(context);
}
}