ASP.NET“禁用"开发环境中的身份验证 [英] Asp.net "disable" authentication in development environment
问题描述
是否可以在不更改其逻辑的情况下禁用" asp.net核心应用程序中的身份验证?
Is it possible to "disable" authentication in asp.net core application without changing its logic?
我有一个.net网站,该网站使用外部身份服务器应用程序进行身份验证. 无论如何,我希望能够在开发身份验证时(ASPNETCORE_ENVIRONMENT =开发)来模拟身份验证,允许对所有操作进行访问,而忽略了授权属性.
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
是有条件绕过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>();
}
注意AddAuthentication
和AddAuthorization
服务仍按照产品代码进行注册和配置(很好).
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!
这篇关于ASP.NET“禁用"开发环境中的身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!