我有以下代碼可以在本地開發期間繞過添加身份驗證,我使用的是 Azure AD 和 .NET Core。
#if !DEBUG
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));
#endif
但是,由于我的控制器受 Authorize 屬性保護,如何在本地開發期間繞過 Controller 內部的 Authorize 屬性:
[Authorize(Roles = "Buyer")]
public class ProductController : ApiBaseController
{
}
在 .NET Framework 中,我有以下代碼來覆寫 Authorize 屬性:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
#if DEBUG
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return true;
}
#endif
}
.NET Core 的等效代碼是什么?或者有沒有其他方法可以覆寫 Startup.cs 類中的 Authorize 屬性?
uj5u.com熱心網友回復:
我認為你可以使用 a IClaimsTransformation。在這種情況下,我只會為每個人添加一個角色,但是當它連接起來時,它只會在您處于開發階段時才這樣做(注意:您需要確保環境變數設定正確才能正常IsDevelopment作業)。
AddRolesClaimsTransformation.cs
/// <summary>
/// Adds roles to a user on the fly, this will hard code a Buyer role for everyone.
/// </summary>
public class AddRolesClaimsTransformation : IClaimsTransformation
{
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
// Clone current identity
var clone = principal.Clone();
var ident = (ClaimsIdentity)clone.Identity;
ident.AddClaim(new Claim(ClaimTypes.Role, "Buyer"));
return clone;
}
}
啟動檔案
// Only in dev
if (builder.Environment.IsDevelopment())
{
builder.Services.AddScoped<IClaimsTransformation, AddRolesClaimsTransformation>();
}
根據 Microsoft 檔案,這應該適用于 ASP.NET Core 3.1。然而,我針對 .NET 6 對其進行了測驗(在 .NET 6 中,新站點的模板將這些Startup.cs內容移到了 .NET 中Program.cs)。
另一方面要注意,如果您依賴于 上的IsDevelopment管道,WebHostEnvironment則不必使用編譯器指令。這樣,一旦環境設定好,它就可以正常作業,但是您將它部署在那里(例如,意外的除錯構建不可能使它進入它不應該在的環境中)。
uj5u.com熱心網友回復:
[Authorize(Roles...您可以使用[Authorize(Policy...來添加一個間接層,而不是顯式指定每個控制器需要的角色。
這樣你就可以在你的StartUp班級(或IConfigureOptions<AuthorizationOptions>服務)中決定每個政策的確切含義。包括您可能有的任何其他奇怪的要求。
[Authorize(Policy= "Buyer")]
public class ProductController : ApiBaseController
...
services.AddAuthorization(o =>
{
o.AddPolicy("Buyer", b => {
#if DEBUG
b.RequireAuthenticatedUser();
#else
b.RequireRole("Buyer");
#endif
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/364413.html
標籤:C# asp.net核心 .net核心 asp.net-core-webapi asp.net-core-3.1
上一篇:使用多個實體時的EF核心并發
下一篇:帶blazor的事件回呼
