Asp.net “disable” authentication in development environment

后端 未结 5 884
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 04:27

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

5条回答
  •  爱一瞬间的悲伤
    2020-12-06 05:04

    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!

提交回复
热议问题