using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Yavsc.Org.Tests; /// /// Middleware that promotes the X-Test-Role request header to /// an authenticated on /// . Lets downstream code (controllers, /// services) call User.GetUserId() and other claim-based /// helpers as if a real login had happened, while /// independently short-circuits /// [Authorize(...)] policy checks. /// /// This middleware is added to the pipeline by /// so it runs after the /// production authentication middleware; setting User before /// UseAuthentication would have it overwritten on the next /// middleware. /// 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); } }