.NET Tips and Tricks

Blog archive

Mocking an Authenticated User in Blazor/ASP.NET Core

I've done a couple of recent columns about securing Blazor Components and using claims-based policies declaratively in ASP.NET Core generally. While working with security, I'm always interested in doing end-to-end testing: Starting up the application and seeing what happens when I try to navigate to a page.

However, while that matters to me, I'm less interested in setting up users with a variety of different security configurations (so many names! so many passwords!). Inevitably while thinking I'm testing one authorization scenario, I pick a user that actually represents a different scenario.

So I created a MockAuthenticatedUser class that, once added to my application's middleware, creates an authenticated user for my application. I find it easier to configure my mock user's authorization claims in code before running a test than it is to maintain (and remember) a variety of users.

If you think you might find it useful, you can add it to your processing pipeline with code like this in your Startup class' ConfigureServices method:

services.AddAuthentication("BasicAuthentication")
                .AddScheme<AuthenticationSchemeOptions, 
                              MockAuthenticatedUser>("BasicAuthentication", null);

To use this class, you'll also need this line in your Startup class' Configure method:

app.UseAuthentication();

I should be clear that I've only used this to test Controllers so it might behave differently with Razor Pages.

Here's the code for my MockAuthenticatedUser class that configures a user with a name, an Id, a role, and some random claims:

using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace SampleBlazor.Models
{
  public class MockAuthenticatedUser : AuthenticationHandler<AuthenticationSchemeOptions>
  {
    const string userId = "phv";
    const string userName = "Jean Irvine";
    const string userRole = "ProductManager";

    public MockAuthenticatedUser(
      IOptionsMonitor<AuthenticationSchemeOptions> options,
      ILoggerFactory logger,
      UrlEncoder encoder,
      ISystemClock clock)
      : base(options, logger, encoder, clock){ }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
      var claims = new[] 
        {
          new Claim(ClaimTypes.NameIdentifier, userId),
          new Claim(ClaimTypes.Name, userName),
          new Claim(ClaimTypes.Role, userRole),
          new Claim(ClaimTypes.Email, "peter.vogel@phvis.com"),
        };
        var identity = new ClaimsIdentity(claims, Scheme.Name);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, Scheme.Name);

        return await Task.FromResult(AuthenticateResult.Success(ticket));
    }
  }
}

Posted by Peter Vogel on 11/14/2019


comments powered by Disqus

Featured

  • Full Stack Hands-On Development with .NET

    In the fast-paced realm of modern software development, proficiency across a full stack of technologies is not just beneficial, it's essential. Microsoft has an entire stack of open source development components in its .NET platform (formerly known as .NET Core) that can be used to build an end-to-end set of applications.

  • .NET-Centric Uno Platform Debuts 'Single Project' for 9 Targets

    "We've reduced the complexity of project files and eliminated the need for explicit NuGet package references, separate project libraries, or 'shared' projects."

  • Creating Reactive Applications in .NET

    In modern applications, data is being retrieved in asynchronous, real-time streams, as traditional pull requests where the clients asks for data from the server are becoming a thing of the past.

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

Subscribe on YouTube