.net core middleware for claims in csharp

Here's a sample implementation of a middleware that adds a claim to the identity of the user:

main.cs
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

public class AddClaimsMiddleware
{
    private readonly RequestDelegate _next;
    private readonly string _claimType;
    private readonly string _claimValue;

    public AddClaimsMiddleware(RequestDelegate next, string claimType, string claimValue)
    {
        _next = next;
        _claimType = claimType;
        _claimValue = claimValue;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var identity = context.User.Identity as ClaimsIdentity;
        identity?.AddClaim(new Claim(_claimType, _claimValue));
        await _next(context);
    }
}

public static class AddClaimsMiddlewareExtensions
{
    public static IApplicationBuilder UseAddClaims(this IApplicationBuilder builder, string claimType, string claimValue)
    {
        return builder.UseMiddleware<AddClaimsMiddleware>(claimType, claimValue);
    }
}
980 chars
34 lines

In this example, we first define a AddClaimsMiddleware class implementing the middleware logic of adding a claim to the current user's identity. We create an extension method UseAddClaims that can be used to add this middleware in the pipeline.

To use this middleware in your application, you can add it to the pipeline with the desired claim type and value:

main.cs
public void Configure(IApplicationBuilder app)
{
    app.UseAuthentication();

    app.UseAddClaims("custom_claim", "some_value");

    app.UseMvc();
}
152 chars
9 lines

This middleware can then be used in the authentication process to add custom claims to the identity of the user.

gistlibby LogSnag