Asp.net “disable” authentication in development environment

后端 未结 5 895
佛祖请我去吃肉
佛祖请我去吃肉 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 04:53

    It's tricky to give a detailed answer without more details on your end, but I have previously achieved this by conditionally registering:

    • the external authentication middleware
    • the global policy that requires an authenticated request

    it looked something like:

    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            Environment = env;
        }
    
        public IHostingEnvironment Environment { get; }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(x =>
            {
                if (!Environment.IsDevelopment())
                {
                    var authenticatedUserPolicy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .Build();
    
                    x.Filters.Add(new AuthorizeFilter(authenticatedUserPolicy));
                }
            });
        }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseStaticFiles();
    
            if (!Environment.IsDevelopment())
            {
                // Register external authentication middleware
            }
    
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
    

    In my case, the authorization filter was applied globally, so every single action of the MVC app required an authenticated user.

    If you have different requirements - fine-grained [Authorize] attributes on some actions - then you could probably achieve the same result by changing how the associated authorization policies are built. They could basically contain no requirements at all.

    AuthorizationPolicy yourCustomPolicy = null;
    if (Environment.IsDevelopment())
    {
        yourCustomPolicy = new AuthorizationPolicyBuilder().Build();
    }
    else
    {
        yourCustomPolicy = new AuthorizationPolicyBuilder()
            // chaining appropriate methods to suit your needs
            .Build();
    }
    

提交回复
热议问题