Skip to content

Instantly share code, notes, and snippets.

@zbartl
Last active June 6, 2017 20:21
Show Gist options
  • Save zbartl/502b0701083621f421fe7eb02ee84751 to your computer and use it in GitHub Desktop.
Save zbartl/502b0701083621f421fe7eb02ee84751 to your computer and use it in GitHub Desktop.
aspnetcore integration test - middleware
public class AuthenticatedTestRequestMiddleware
{
public const string TestingCookieAuthentication = "TestCookieAuthentication";
public const string TestingHeader = "X-Integration-Testing";
public const string TestingHeaderValue = "abcde-12345";
private readonly RequestDelegate _next;
public AuthenticatedTestRequestMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Headers.Keys.Contains(TestingHeader) &&
context.Request.Headers[TestingHeader].First().Equals(TestingHeaderValue))
{
if (context.Request.Headers.Keys.Contains("my-name"))
{
var name =
context.Request.Headers["my-name"].First();
var id =
context.Request.Headers.Keys.Contains("my-id")
? context.Request.Headers["my-id"].First() : "";
ClaimsIdentity claimsIdentity = new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.Name, name),
new Claim(ClaimTypes.NameIdentifier, id),
}, TestingCookieAuthentication);
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
context.User = claimsPrincipal;
}
}
await _next(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment