ASP.NET Core 在开发环境中禁用身份验证 [英] ASP.NET Core disable authentication in development environment

查看:83
本文介绍了ASP.NET Core 在开发环境中禁用身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以禁用"ASP.NET Core 应用程序中的身份验证而不改变其逻辑?

Is it possible to "disable" authentication in ASP.NET Core application without changing its logic?

我有一个 .net 网站,它使用外部身份服务器应用程序进行身份验证.无论如何,我希望能够在我开发它时模拟身份验证 (ASPNETCORE_ENVIRONMENT = Development),播放对所有操作的访问权限,而忽略授权属性.

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?

推荐答案

更新到 net core 3.1 后,mvc AllowAnonymousFilter 不再为我们工作.我们发现有条件地添加自定义 IAuthorizationHander 是有条件地绕过身份验证的最简单方法.

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 服务仍然按照 prod 代码注册和配置(这很好).

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!

这篇关于ASP.NET Core 在开发环境中禁用身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆