且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET“禁用"开发环境中的身份验证

更新时间:2022-12-06 17:14:28

在更新到Net Core 3.1时,mvc AllowAnonymousFilter不再对我们有用.我们发现有条件地添加自定义IAuthorizationHander是有条件绕过auth的最简单方法.

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.

例如

/// <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;
    }
}

然后有条件地在Startup.ConfigureServices中注册此处理程序.

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>();
}

注意AddAuthenticationAddAuthorization服务仍按照产品代码进行注册和配置(很好).

Note AddAuthentication and AddAuthorization services are still registered and configured as per prod code (which is nice).

为了允许我们的单元测试绕过auth,我们添加了一个带有启动类的新匿名测试库,该类在没有任何条件的情况下添加了该行.很好,很简单!

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!