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.
This commit is contained in:
parent
68192f9e5b
commit
afd02ab5aa
3 changed files with 102 additions and 39 deletions
46
src/Yavsc.Org.Tests/TestUserMiddleware.cs
Normal file
46
src/Yavsc.Org.Tests/TestUserMiddleware.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
47
src/Yavsc.Org.Tests/TestUserStartupFilter.cs
Normal file
47
src/Yavsc.Org.Tests/TestUserStartupFilter.cs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
|
||||
namespace Yavsc.Org.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Startup filter that injects <see cref="TestUserMiddleware"/> after
|
||||
/// the authentication and authorization middleware. The
|
||||
/// <see cref="IStartupFilter.Configure"/> contract wraps the existing
|
||||
/// pipeline: the <c>next</c> delegate is the rest of the app's
|
||||
/// pipeline, so we run our middleware <em>before</em> it but
|
||||
/// <em>after</em> anything that was registered as a startup filter
|
||||
/// earlier in the chain.
|
||||
///
|
||||
/// In practice this puts <c>TestUserMiddleware</c> ahead of
|
||||
/// <c>UseAuthentication</c> (registered inside <c>ConfigurePipeline</c>)
|
||||
/// because the production code path runs <c>UseAuthentication</c>
|
||||
/// synchronously inside <c>Configure</c>, after all startup filters
|
||||
/// have wrapped it. We want the opposite: the test identity must be
|
||||
/// visible to authorization and the controller, so we register
|
||||
/// <c>TestUserMiddleware</c> via <see cref="IApplicationBuilder.Use"/>
|
||||
/// inside the filter such that it runs late in the chain. The
|
||||
/// simplest way to achieve that is to register the middleware
|
||||
/// after the production authorization pipeline: we wrap with our
|
||||
/// middleware inside the filter, so our delegate sits between the
|
||||
/// framework middleware (set up by Configure) and the rest of the
|
||||
/// pipeline — meaning requests flow:
|
||||
/// framework authN/authZ → TestUserMiddleware → next pipeline.
|
||||
/// </summary>
|
||||
public class TestUserStartupFilter : IStartupFilter
|
||||
{
|
||||
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
|
||||
{
|
||||
return app =>
|
||||
{
|
||||
// Replay the production pipeline first (this is what
|
||||
// Program.Main + ConfigurePipeline set up, including
|
||||
// UseAuthentication and UseAuthorization).
|
||||
next(app);
|
||||
// Then add our middleware on top. UseMiddleware<T> wires
|
||||
// it through the same IMiddlewareActivator the framework
|
||||
// uses, so the dependency on TestUserMiddleware is
|
||||
// resolved from the request scope.
|
||||
app.UseMiddleware<TestUserMiddleware>();
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,11 +1,8 @@
|
|||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yavsc.Org.Tests;
|
||||
|
||||
|
|
@ -19,10 +16,10 @@ namespace Yavsc.Org.Tests;
|
|||
/// <c>[Authorize("AdministratorOnly")]</c> (and any other policy
|
||||
/// requiring a role) is satisfied by sending an
|
||||
/// <c>X-Test-Role: Administrator</c> header, without a real login.
|
||||
/// Also injects a middleware that promotes the same header into a
|
||||
/// real <see cref="ClaimsPrincipal"/> on <c>HttpContext.User</c> so
|
||||
/// that user code reading <c>User.GetUserId()</c> sees a logged-in
|
||||
/// identity.
|
||||
/// Also adds <see cref="TestUserStartupFilter"/> which installs
|
||||
/// <see cref="TestUserMiddleware"/> so that <c>User.GetUserId()</c>
|
||||
/// in user code sees a logged-in identity derived from the same
|
||||
/// header.
|
||||
/// </summary>
|
||||
public class TestWebApplicationFactory : WebApplicationFactory<Program>
|
||||
{
|
||||
|
|
@ -39,39 +36,12 @@ public class TestWebApplicationFactory : WebApplicationFactory<Program>
|
|||
// the test one. The default registered by AddAuthorization
|
||||
// becomes irrelevant: any GetPolicyAsync call is routed here.
|
||||
services.AddSingleton<IAuthorizationPolicyProvider, TestAuthPolicyProvider>();
|
||||
});
|
||||
|
||||
// Promote the X-Test-Role header to an authenticated identity
|
||||
// on the request, so anything that reads User.GetUserId() (or
|
||||
// any other claim-based helper) downstream sees a logged-in
|
||||
// user. The policy provider above only short-circuits
|
||||
// [Authorize(...)] checks; it does not touch HttpContext.User.
|
||||
builder.Configure(app =>
|
||||
{
|
||||
app.Use(InjectTestUser);
|
||||
// Register the test middleware and its startup filter.
|
||||
// The startup filter wraps the production pipeline so
|
||||
// TestUserMiddleware runs after UseAuthentication/Authorization.
|
||||
services.AddTransient<TestUserMiddleware>();
|
||||
services.AddTransient<IStartupFilter, TestUserStartupFilter>();
|
||||
});
|
||||
}
|
||||
|
||||
private static RequestDelegate InjectTestUser(RequestDelegate next)
|
||||
{
|
||||
return async ctx =>
|
||||
{
|
||||
var role = ctx.Request.Headers[TestAuthPolicyProvider.HeaderName].ToString();
|
||||
if (!string.IsNullOrEmpty(role) &&
|
||||
(ctx.User.Identity is null || !ctx.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, "test-user"),
|
||||
},
|
||||
authenticationType: "TestAuth");
|
||||
ctx.User = new ClaimsPrincipal(identity);
|
||||
}
|
||||
await next(ctx);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue