易於使用且非常輕量級的 Microsoft 風格的 ASP.NET Core 基本方案驗證實作。
在 GitHub 上查看
.NET Framework 4.6.1 和/或 NetStandard 2.0 以上版本
多目標:net8.0; NET7.0; NET6.0; NET5.0; netcoreapp3.1; netcoreapp3.0;網路標準2.0;網路461
該庫發佈在 NuGet 上。因此,如果您希望使用 NuGet 套件而不對程式碼進行任何自訂更改,則可以將其直接安裝到您的專案中。
直接從下面的連結下載。請考慮下載新軟體包,因為舊軟體包已過時。
新包連結 - AspNetCore.Authentication.Basic。
舊包連結 - Mihir.AspNetCore.Authentication.Basic。
或透過在您的專案上執行以下命令。
PM> Install-Package AspNetCore.Authentication.Basic
範例可在範例目錄下找到。
設定非常簡單。您需要具備 ASP.NET Core 2.0 或更高版本的基本工作知識才能開始使用此程式庫。
有兩種不同的方式使用這個函式庫來完成它的工作。如果需要,兩種方式可以混合使用。
1]使用IBasicUserValidationService的實現
2]使用BasicOptions.Events (OnValidateCredentials委託),這與您在Microsoft的身份驗證庫中找到的方法相同
筆記:
如果未設定 SuppressWWWAuthenticateHeader,則需要在選項中設定 Realm。
如果使用 IBasicUserValidationService 介面的實作並且也設定了 BasicOptions.Events.OnValidateCredentials 委託,則會先使用此委託。
使用基本驗證時,請務必在生產中使用 HTTPS(SSL 憑證)協定。
using AspNetCore.Authentication.Basic;public class Startup{public void ConfigureServices(IServiceCollection services){// 如果未設定 SuppressWWWWAuthenticateHeader,則需要在選項中設定 Realm。已設置,然後將首先使用此委託。 "My App" });// 下面帶有型別參數的AddBasic 將會將BasicUserValidationService 加入到依賴容器中。 .AddBasic<BasicUserValidationService>(options => { options.Realm = "My App"; });services.AddControllers();//// 預設情況下,不會對每個請求進行身份驗證,這是ASP. NET Core 的預設意圖//// 因此,若要對每個要求進行驗證,請使用下面的FallbackPolicy 選項。 RequireAuthenticatedUser().Build(); //});}public void Configure(IApplicationBuilder app, IHostingEnvironment env){app.UseHttpsRedirection();// 下面的管道鏈順序很重要! ();app.UseAuthorization( );app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}}
using AspNetCore.Authentication.Basic;public class Startup{public void ConfigureServices(IServiceCollection services){// 如果未設定 SuppressWWWWAuthenticateHeader,則需要在選項中設定 Realm。已設置,然後將首先使用此委託。 "My App" });// 下面帶有型別參數的AddBasic 將會將BasicUserValidationService 加入到依賴容器中。 .AddBasic<BasicUserValidationService>(options => { options.Realm = "My App"; });services.AddMvc();//// 預設情況下,不會對每個請求進行身份驗證,這是ASP. NET Core 的預設意圖行為。 / options.Filters.Add(new AuthorizeFilter(new) AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));//});}public void Configure(IApplicationBuilder app, IHostingEnvironment env){app.UseappA); .UseMvc();}}
使用AspNetCore.Authentication.Basic;公共類別BasicUserValidationService : IBasicUserValidationService{私人唯讀ILogger<BasicUserValidationService> _logger;私人唯讀IUserRepository _userRepositoryory; Repository = userRepository; }公共非同步Task<bool> IsValidAsync(字串使用者名,字串密碼){try{// 注意:請勿使用此實作。這僅用於演示目的// 在此處編寫您的實現並根據驗證返回true 或false..var user = wait _userRepository.GetUserByUsername(username);var isValid = user != null && user.Password == password; return isValid;}catch(異常e){_logger.LogError(e,e.Message);拋出;}}}
如果 SuppressWWWAuthenticateHeader 未設定為 true,則需要設定。當質疑未經身份驗證的請求時,它與 WWW-Authenticate 回應標頭一起使用。
預設值為 false。
如果設定為 true,則在挑戰未經驗證的請求時不會傳回 WWW-Authenticate 回應標頭。
如果設定為 false,則在挑戰未經身份驗證的請求時將傳回 WWW-Authenticate 回應標頭。
預設值為 false。
如果設定為 true,它會檢查是否允許匿名過濾端點上的控制器操作或元數據,如果找到,它不會嘗試對請求進行身份驗證。
應用程式提供的對象,用於處理基本驗證中間件引發的事件。
應用程式可以完全實作該接口,也可以建立 BasicEvents 的實例並僅將委託分配給它想要處理的事件。
指派給該屬性的委託將在驗證憑證之前被呼叫。
您必須為此屬性提供委託才能進行身份驗證。
在您的委託中,您應該調用context.ValidationSucceeded() ,它將根據用戶詳細資訊處理身份驗證聲明主體的構造,該用戶詳細資訊將被分配context.Principal 屬性並調用context.Success() ,或從使用者建構身份驗證聲明主體詳細資訊並將其指派給 context.Principal 屬性,最後呼叫 context.Success() 方法。
如果僅設定 context.Principal 屬性而不呼叫 context.Success() 方法,則自動呼叫 Success() 方法。
當身份驗證成功時,將呼叫指派給此屬性的委託。如果分配了 OnValidateCredentials 委託,則不會呼叫它。
它可用於向回應添加聲明、標頭等。
當庫中拋出任何意外異常時,將呼叫指派給此屬性的委託。
在處理未經授權的回應時,將在將質詢傳送回呼叫者之前呼叫指派給此屬性的委託。
僅當您知道自己在做什麼並且想要使用自訂實作時才使用此選項。 如果相關身份驗證方案將身份驗證互動作為其請求流的一部分進行處理,則設定委託來處理 401 質詢問題。 (例如新增回應標頭,或將登入頁面或外部登入位置的 401 結果變更為 302。)
最後呼叫 context.Handled() ,以便跳過此挑戰的任何預設邏輯。
如果授權失敗並導致禁止回應,則將呼叫指派給此屬性的委託。
僅當您知道自己在做什麼並且想要使用自訂實作時才使用此選項。
設定委託來處理禁止。
最後呼叫 context.Handled() ,以便跳過任何預設邏輯。
使用 ASP.NET Core,預設不會對所有請求進行驗證。因此,如果您未通過請求傳遞所需的基本身份驗證詳細信息,如果您的BasicUserValidationService未命中,請不要擔心。這是正常行為。只有在透過使用[Authorize]過濾器屬性裝飾控制器/方法或透過其他方式明確告知 ASP.NET Core 進行身份驗證時,ASP.NET Core 才會發起身份驗證挑戰。
但是,如果您希望預設所有請求都進行質詢身份驗證,則根據您所使用的內容,您可以將下列選項行新增至Startup類別的ConfigureServices方法。
// 在ASP.NET Core 3.0 上services.AddAuthorization(options =>{options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();});// 或// 在ASP.NET Core 2.0 上servicesservices .AddMvc (選項=> {options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));});
如果您不使用 MVC,而是在 ASP.NET Core 3.0 或更高版本上使用 Endpoints,則可以將鏈方法.RequireAuthorization()
新增至Startup類別上的Configure方法下的端點映射,如下所示。
// ASP.NET Core 3.0 以上app.UseEndpoints(endpoints =>{endpoints.MapGet("/", async context =>{await context.Response.WriteAsync("Hello World!");}).RequireAuthorization() ; / / 注意這裡! !
ASP.NET Core 支援新增多個驗證方案,該程式庫也支援。只需使用以方案名稱作為參數的擴充方法即可。其餘的都一樣。這可以透過許多不同的方式來實現。下面只是一個簡單的範例。
請注意,方案名稱參數可以是您想要的任何字串。
公共無效ConfigureServices(IServiceCollection服務){services.AddTransient <IUserRepository,InMemoryUserRepository>();services.AddAuthentication(“Scheme1”).AddBasic <BasicUserValidationService>(“Scheme1”,選項=>>Rem ”; }).AddBasic<BasicUserValidationService_2>("Scheme2", options => { options.Realm = "我的應用程式"; }).AddBasic("Scheme3", options => { options.Realm = "我的應用程式"; options.Events = new BasicEvents{OnValidateCredentials = async (context) =>{var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();var user = wait userRepository.GetUserUserUserRepositorySname! = null && user.Password == context.Password;if (isValid){context.Response.Headers.Add("ValidationCustomHeader", "From OnValidateCredentials");var Claims = new[]{new Claim("CustomClaimType", "自訂聲明值- 來自OnValidateCredentials")};context.ValidationSucceeded(claims); // 宣告是可選的}else{context.ValidationFailed();}}}});services.AddControllers();services.AddAuthorization(options =>{options.FallbackPolicy = new AuthorizationPolicyBuilder("Scheme1", "Scheme2" , " Scheme3").RequireAuthenticatedUser().Build();});}
版本 | 筆記 |
---|---|
8.0.0 |
|
7.0.0 |
|
6.0.1 |
|
5.1.0 |
|
5.0.0 |
|
3.1.1 |
|
3.1.0 |
|
2.2.0 |
|
RFC 7617:HTTP Basic 的技術規範
ASP.NET Core 安全性文檔
ASPNET/安全
麻省理工學院許可證