Skip to content

Instantly share code, notes, and snippets.

@markrendle
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markrendle/99146b055a0933bbe861 to your computer and use it in GitHub Desktop.
Save markrendle/99146b055a0933bbe861 to your computer and use it in GitHub Desktop.
Middleware example
using System.Linq;
using Microsoft.AspNet.Builder;
namespace StealthProject.Mvc
{
public static class AuthenticationMiddleware
{
private static readonly char[] Eq = { '=' };
public static IApplicationBuilder UseHeaderClaims(this IApplicationBuilder app)
{
// Use an OWIN-style "middleware delegate"
return app.Use(next => async context =>
{
string[] claims;
if (!context.Request.Headers.TryGetValue("JWT-Claim", out claims))
{
context.Response.StatusCode = 401;
return;
}
var dict = claims.Select(c => c.Split(Eq, 2))
.ToDictionary(a => a[0], a => a[1]);
context.User = ClaimsPrincipalBuilder.FromDictionary(dict);
await next(context);
});
}
}
}

So the application this is used in is sitting behind an Nginx proxy with embedded Lua script that validates JSON Web Tokens and extracts the token properties into headers of the form:

JWT-Claim: email=bob@example.com
JWT-Claim: subType=Platinum

This means no actual verification is required in the .NET code, but we still want to create a ClaimsPrincipal for the HttpContext.

The extension method shown above means that in the Startup.Configure method, we just have to call:

public void Configure(IApplicationBuilder app)
{
    // ...

    app.UseHeaderClaims();

    // ...
}
using System.Linq;
using Microsoft.AspNet.Builder;
namespace StealthProject.Mvc
{
public static class NoOpMiddleware
{
private static readonly char[] Eq = { '=' };
public static IApplicationBuilder UseNoOp(this IApplicationBuilder app)
{
return app.Use(next => async context =>
{
await next(context);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment