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 for authentication. Anyway I would like to be able to mock the authentication when I'm developing it (ASPNETCORE_ENVIRONMENT = Development), airing access to all actions ignoring the authorization attributes.
Is it possible to do it just mocking some services in the service collection?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With