ASP.NET Core disable authentication in development environment

On updating to net core 3.1, the mvc AllowAnonymousFilter was not working for us any more. We found conditionally adding a custom IAuthorizationHander to be the simplest way forward to conditionally bypass auth.

eg.

/// <summary>
/// This authorisation handler will bypass all requirements
/// </summary>
public class AllowAnonymous : IAuthorizationHandler
{
    public Task HandleAsync(AuthorizationHandlerContext context)
    {
        foreach (IAuthorizationRequirement requirement in context.PendingRequirements.ToList())
            context.Succeed(requirement); //Simply pass all requirements
        
        return Task.CompletedTask;
    }
}

Then register this handler conditionally in Startup.ConfigureServices.

private readonly IWebHostEnvironment _env;
public Startup(IWebHostEnvironment env)
{
    _env = env;
}

public void ConfigureServices(IServiceCollection services)
{
  {...}

  //Allows auth to be bypassed
  if (_env.IsDevelopment())
    services.AddSingleton<IAuthorizationHandler, AllowAnonymous>();
}

Note AddAuthentication and AddAuthorization services are still registered and configured as per prod code (which is nice).

To allow our unit test to bypass auth, we added a new anonymous testbase with a startup class that added this line without any conditions. Nice and simple!

Leave a Comment