A quick helper method to display user claims

November 29, 2019
ASP.NET Core 3.0

In most of the projects that I work on, at some point during the development process, I run into a scenario where I need to inspect a user’s claims. This most often happens when I work with external authentication services via OpenID Connect, and I want to inspect the claims returned by the Identity Provider.

Of course, one way is to set a debugger breakpoint in your code and inspect the User property of your PageModel to view the claims.

Inspect user claims via debugger

However, this requires you to be running in debug mode, which is not necessarily something I want to do.

So, I have created a helper extension method that I include in all my projects which displays all the user’s claims in an HTML table.

public static class RouteBuilderExtensions
{
    public static void MapClaims(this IEndpointRouteBuilder endpoints)
    {
        endpoints.MapGet("/claims", async context =>
        {
            var sb = new StringBuilder();
            if (context.User.Identity.IsAuthenticated)
            {
                sb.Append("<h1>User claims</h1>");
                sb.Append("<table border=\"1\"><thead>");
                sb.Append("<tr><th>Type</th><th>Value</th><th>Issuer</th></tr>");
                sb.Append("</thead><tbody>");
                foreach (var claim in context.User.Claims)
                {
                    sb.Append("<tr>");
                    sb.Append($"<td>{claim.Type}</td>");
                    sb.Append($"<td>{claim.Value}</td>");
                    sb.Append($"<td>{claim.Issuer}</td>");
                    sb.Append("</tr>");
                }

                sb.Append("</tbody></table>");

                await context.Response.WriteAsync(sb.ToString());
            }
        });
    }
}

You can then use this extension method when mapping the endpoints for your application. In the sample below, I only map the endpoint when running locally in development mode.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //...

    app.UseEndpoints(endpoints =>
    {
        if (env.IsDevelopment())
        {
           endpoints.MapClaims();
        }

        endpoints.MapRazorPages();
    });
}

When running your application, you can go to the /claims route to see the user’s claims.

User claims displayed in the browser

PS: If you need assistance on any of your ASP.NET Core projects, I am available for hire for freelance work.