Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core disable authentication in development environment

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?

like image 220
fra Avatar asked Dec 13 '16 01:12

fra


Video Answer


1 Answers

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!

like image 73
Simon Hooper Avatar answered Sep 18 '22 12:09

Simon Hooper