您好,登錄后才能下訂單哦!
本篇文章為大家展示了使用ASP.NET Core 實現基本認證,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
HTTP基本認證
在HTTP中,HTTP基本認證(Basic Authentication)是一種允許網頁瀏覽器或其他客戶端程序以(用戶名:口令) 請求資源的身份驗證方式,不要求cookie,session identifier、login page等標記或載體。
- 所有瀏覽器據支持HTTP基本認證方式
- 基本身證原理不保證傳輸憑證的安全性,僅被based64編碼,并沒有encrypted或者hashed,一般部署在客戶端和服務端互信的網絡,在公網中應用BA認證通常與https結合
BA標準協議
BA認證協議的實施主要依靠約定的請求頭/響應頭,典型的瀏覽器和服務器的BA認證流程:
① 瀏覽器請求應用了BA協議的網站,服務端響應一個401認證失敗響應碼,并寫入WWW-Authenticate響應頭,指示服務端支持BA協議
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="our site" # WWW-Authenticate響應頭包含一個realm域屬性,指明HTTP基本認證的是這個資源集
或客戶端在第一次請求時發送正確Authorization標頭,從而避免被質詢
② 客戶端based64(用戶名:口令),作為Authorization標頭值 重新發送請求。
Authorization: Basic userid:password
所以在HTTP基本認證中認證范圍與 realm有關(具體由服務端定義)
> 一般瀏覽器客戶端對于www-Authenticate質詢結果,會彈出口令輸入窗.
BA編程實踐
aspnetcore網站利用FileServerMiddleware 將路徑映射到某文件資源, 現對該 文件資源訪問路徑應用 Http BA協議。
ASP.NET Core服務端實現BA認證:
① 實現服務端基本認證的認證過程、質詢邏輯
②實現基本身份認證交互中間件BasicAuthenticationMiddleware ,要求對HttpContext使用 BA.Scheme
③ASP.NET Core 添加認證計劃 , 為文件資源訪問路徑啟用 BA中間件,注意使用UseWhen插入中間件
using System; using System.Net.Http.Headers; using System.Security.Claims; using System.Text; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace EqidManager.Services { public static class BasicAuthenticationScheme { public const string DefaultScheme = "Basic"; } public class BasicAuthenticationOption:AuthenticationSchemeOptions { public string Realm { get; set; } public string UserName { get; set; } public string UserPwd { get; set; } } public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOption> { private readonly BasicAuthenticationOption authOptions; public BasicAuthenticationHandler( IOptionsMonitor<BasicAuthenticationOption> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { authOptions = options.CurrentValue; } /// <summary> /// 認證 /// </summary> /// <returns></returns> protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { if (!Request.Headers.ContainsKey("Authorization")) return AuthenticateResult.Fail("Missing Authorization Header"); string username, password; try { var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]); var credentialBytes = Convert.FromBase64String(authHeader.Parameter); var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':'); username = credentials[0]; password = credentials[1]; var isValidUser= IsAuthorized(username,password); if(isValidUser== false) { return AuthenticateResult.Fail("Invalid username or password"); } } catch { return AuthenticateResult.Fail("Invalid Authorization Header"); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier,username), new Claim(ClaimTypes.Name,username), }; var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return await Task.FromResult(AuthenticateResult.Success(ticket)); } /// <summary> /// 質詢 /// </summary> /// <param name="properties"></param> /// <returns></returns> protected override async Task HandleChallengeAsync(AuthenticationProperties properties) { Response.Headers["WWW-Authenticate"] = $"Basic realm=\"{Options.Realm}\""; await base.HandleChallengeAsync(properties); } /// <summary> /// 認證失敗 /// </summary> /// <param name="properties"></param> /// <returns></returns> protected override async Task HandleForbiddenAsync(AuthenticationProperties properties) { await base.HandleForbiddenAsync(properties); } private bool IsAuthorized(string username, string password) { return username.Equals(authOptions.UserName, StringComparison.InvariantCultureIgnoreCase) && password.Equals(authOptions.UserPwd); } } }
// HTTP基本認證Middleware public static class BasicAuthentication { public static void UseBasicAuthentication(this IApplicationBuilder app) { app.UseMiddleware<BasicAuthenticationMiddleware>(); } } public class BasicAuthenticationMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public BasicAuthenticationMiddleware(RequestDelegate next, ILoggerFactory LoggerFactory) { _next = next; _logger = LoggerFactory.CreateLogger<BasicAuthenticationMiddleware>(); } public async Task Invoke(HttpContext httpContext, IAuthenticationService authenticationService) { var authenticated = await authenticationService.AuthenticateAsync(httpContext, BasicAuthenticationScheme.DefaultScheme); _logger.LogInformation("Access Status:" + authenticated.Succeeded); if (!authenticated.Succeeded) { await authenticationService.ChallengeAsync(httpContext, BasicAuthenticationScheme.DefaultScheme, new AuthenticationProperties { }); return; } await _next(httpContext); } }
// HTTP基本認證Middleware public static class BasicAuthentication { public static void UseBasicAuthentication(this IApplicationBuilder app) { app.UseMiddleware<BasicAuthenticationMiddleware>(); } } public class BasicAuthenticationMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public BasicAuthenticationMiddleware(RequestDelegate next, ILoggerFactory LoggerFactory) { _next = next; _logger = LoggerFactory.CreateLogger<BasicAuthenticationMiddleware>(); } public async Task Invoke(HttpContext httpContext, IAuthenticationService authenticationService) { var authenticated = await authenticationService.AuthenticateAsync(httpContext, BasicAuthenticationScheme.DefaultScheme); _logger.LogInformation("Access Status:" + authenticated.Succeeded); if (!authenticated.Succeeded) { await authenticationService.ChallengeAsync(httpContext, BasicAuthenticationScheme.DefaultScheme, new AuthenticationProperties { }); return; } await _next(httpContext); } }
Startup.cs 文件添加并啟用HTTP基本認證
services.AddAuthentication(BasicAuthenticationScheme.DefaultScheme) .AddScheme<BasicAuthenticationOption, BasicAuthenticationHandler>(BasicAuthenticationScheme.DefaultScheme,null); app.UseWhen( predicate:x => x.Request.Path.StartsWithSegments(new PathString(_protectedResourceOption.Path)), configuration:appBuilder => { appBuilder.UseBasicAuthentication(); } );
以上BA認證的服務端已經完成,現在可以在瀏覽器測試:
進一步思考?
瀏覽器在BA協議中行為: 編程實現BA客戶端,要的同學可以直接拿去
/// <summary> /// BA認證請求Handler /// </summary> public class BasicAuthenticationClientHandler : HttpClientHandler { public static string BAHeaderNames = "authorization"; private RemoteBasicAuth _remoteAccount; public BasicAuthenticationClientHandler(RemoteBasicAuth remoteAccount) { _remoteAccount = remoteAccount; AllowAutoRedirect = false; UseCookies = true; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var authorization = $"{_remoteAccount.UserName}:{_remoteAccount.Password}"; var authorizationBased64 = "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization)); request.Headers.Remove(BAHeaderNames); request.Headers.Add(BAHeaderNames, authorizationBased64); return base.SendAsync(request, cancellationToken); } } // 生成basic Authentication請求 services.AddHttpClient("eqid-ba-request", x => x.BaseAddress = new Uri(_proxyOption.Scheme +"://"+ _proxyOption.Host+":"+_proxyOption.Port ) ) .ConfigurePrimaryHttpMessageHandler(y => new BasicAuthenticationClientHandler(_remoteAccount){} ) .SetHandlerLifetime(TimeSpan.FromMinutes(2)); 仿BA認證協議中的瀏覽器行為
上述內容就是使用ASP.NET Core 實現基本認證,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。