我想到兩種可能的解決方案。
第一個是使用假的Authentication Middleware
。您可以創建一個虛假的身份驗證中間件,如this。而你應該Startup.cs
是這樣的(你應該照顧假服務):
private IHostingEnvironment _env;
public Startup(IHostingEnvironment env)
{
_env = env;
// other stuff
}
public void ConfigureServices(IServiceCollection services)
{
// ...
if (_env.IsDevelopment())
{
// dev stuff
services.AddTransient<ISomeService, FakeSomeService>();
}
else
{
// production stuff
services.AddTransient<ISomeService, SomeService>();
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseFakeAuthentication();
}
else
{
app.UseRealAuthentication();
}
}
二是使用一個以上的處理器(如@Tseng說的)。在這種情況下,我會寫這樣的東西:
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<IAuthorizationHandler, FakeAuthorizationHandler>();
}
else
{
// production stuff
services.AddSingleton<IAuthorizationHandler, RealAuthorizationHandler>();
}
}
你不應該從'AuthorizeAttribute'派生。研究基於策略的授權。 https://docs.asp.net/en/latest/security/authorization/policies.html您可以編寫具有多於1個處理程序的需求,並在第一個不授權的情況下使用不同的處理程序作爲回退(除非第一個調用'context.Failed()')。後備示例可以在這裏找到https://docs.asp.net/en/latest/security/authorization/policies.html#why-would-i-want-multiple-handlers-for-a-requirement – Tseng
謝謝@Tseng那就是好的信息。然而,令人沮喪的是,看起來好像我們失去了根據是否在DEBUG或RELEASE模式下開啓/關閉auth的能力。所以我正確地假設,我可以在#if DEBUG指令**或**上連接一些策略/需求/處理程序,以在一箇中心位置執行所有**我的[授權]屬性**。那該怎麼看? – SteveT
嗯,是的。但是沒有什麼能阻止你創建一個基本需求類,其中你的所有其他需求都來自於這個基礎需求,並且在那裏添加這個檢查 – Tseng