Is it possible to \"disable\" authentication in asp.net core application without changing its logic?
I have a .net website which uses an external identity server app
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.
///
/// This authorisation handler will bypass all requirements
///
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();
}
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 line this line without any conditions. Nice and simple!