Bypass Authorize Attribute in .Net Core for Release Version

前端 未结 6 1954
梦如初夏
梦如初夏 2020-12-07 02:20

Is there a way to \"bypass\" authorization in asp.net core? I noticed that the Authorize attribute no longer has a AuthorizeCore method with which you could use to make dec

6条回答
  •  天命终不由人
    2020-12-07 02:56

    Two possible solutions coming to my mind.

    First is to use fake Authentication Middleware. You can create a fake authentication middleware like this. And your Startup.cs should be something like this(you should take care of fake services):

    private IHostingEnvironment _env;
    
    public Startup(IHostingEnvironment env)
    {
      _env = env;
      // other stuff
    }
    
    public void ConfigureServices(IServiceCollection services)
    {
      // ...
      if (_env.IsDevelopment())
      {
        // dev stuff
        services.AddTransient();
      }
      else
      {
        // production stuff
        services.AddTransient();
      }
    }
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
         if (env.IsDevelopment())
         {
             app.UseFakeAuthentication();
         }
         else
         {
             app.UseRealAuthentication();
         }
    }
    

    Second is to use more than one handlers(as @Tseng said). In this case i would write something like this:

    private IHostingEnvironment _env;
    
    public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
    {
      _env = env;
      // other stuff
    }
    
    public void ConfigureServices(IServiceCollection services)
    {
      // ...
      if (_env.IsDevelopment())
      {
        // dev stuff
         services.AddSingleton();
      }
      else
      {
        // production stuff
        services.AddSingleton();
      }
    }
    

提交回复
热议问题