ASP.NET Core 實現(xiàn)基本認(rèn)證的示例代碼
HTTP基本認(rèn)證
在HTTP中,HTTP基本認(rèn)證(Basic Authentication)是一種允許網(wǎng)頁瀏覽器或其他客戶端程序以(用戶名:口令) 請求資源的身份驗證方式,不要求cookie,session identifier、login page等標(biāo)記或載體。
- 所有瀏覽器據(jù)支持HTTP基本認(rèn)證方式
- 基本身證原理不保證傳輸憑證的安全性,僅被based64編碼,并沒有encrypted或者h(yuǎn)ashed,一般部署在客戶端和服務(wù)端互信的網(wǎng)絡(luò),在公網(wǎng)中應(yīng)用BA認(rèn)證通常與https結(jié)合
https://en.wikipedia.org/wiki/Basic_access_authentication
BA標(biāo)準(zhǔn)協(xié)議
BA認(rèn)證協(xié)議的實施主要依靠約定的請求頭/響應(yīng)頭,典型的瀏覽器和服務(wù)器的BA認(rèn)證流程:
① 瀏覽器請求應(yīng)用了BA協(xié)議的網(wǎng)站,服務(wù)端響應(yīng)一個401認(rèn)證失敗響應(yīng)碼,并寫入WWW-Authenticate響應(yīng)頭,指示服務(wù)端支持BA協(xié)議
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="our site" # WWW-Authenticate響應(yīng)頭包含一個realm域?qū)傩?,指明HTTP基本認(rèn)證的是這個資源集
或客戶端在第一次請求時發(fā)送正確Authorization標(biāo)頭,從而避免被質(zhì)詢
② 客戶端based64(用戶名:口令),作為Authorization標(biāo)頭值 重新發(fā)送請求。
Authorization: Basic userid:password

所以在HTTP基本認(rèn)證中認(rèn)證范圍與 realm有關(guān)(具體由服務(wù)端定義)
> 一般瀏覽器客戶端對于www-Authenticate質(zhì)詢結(jié)果,會彈出口令輸入窗.
BA編程實踐
aspnetcore網(wǎng)站利用FileServerMiddleware 將路徑映射到某文件資源, 現(xiàn)對該 文件資源訪問路徑應(yīng)用 Http BA協(xié)議。
ASP.NET Core服務(wù)端實現(xiàn)BA認(rèn)證:
① 實現(xiàn)服務(wù)端基本認(rèn)證的認(rèn)證過程、質(zhì)詢邏輯
②實現(xiàn)基本身份認(rèn)證交互中間件BasicAuthenticationMiddleware ,要求對HttpContext使用 BA.Scheme
③ASP.NET Core 添加認(rèn)證計劃 , 為文件資源訪問路徑啟用 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>
/// 認(rèn)證
/// </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>
/// 質(zhì)詢
/// </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>
/// 認(rèn)證失敗
/// </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基本認(rèn)證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基本認(rèn)證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基本認(rèn)證
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認(rèn)證的服務(wù)端已經(jīng)完成,現(xiàn)在可以在瀏覽器測試:

進(jìn)一步思考?
瀏覽器在BA協(xié)議中行為: 編程實現(xiàn)BA客戶端,要的同學(xué)可以直接拿去
/// <summary>
/// BA認(rèn)證請求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認(rèn)證協(xié)議中的瀏覽器行為
That's All . BA認(rèn)證是隨處可見的基礎(chǔ)認(rèn)證協(xié)議,本文期待以最清晰的方式幫助你理解協(xié)議:
實現(xiàn)了基本認(rèn)證協(xié)議服務(wù)端,客戶端;
到此這篇關(guān)于ASP.NET Core 實現(xiàn)基本認(rèn)證的示例代碼的文章就介紹到這了,更多相關(guān)ASP.NET Core基本認(rèn)證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- ASP.NET Core3.1 Ocelot認(rèn)證的實現(xiàn)
- ASP.NET Core使用JWT認(rèn)證授權(quán)的方法
- 深入解讀ASP.NET Core身份認(rèn)證過程實現(xiàn)
- ASP.NET Core學(xué)習(xí)之使用JWT認(rèn)證授權(quán)詳解
- ASP.NET Core Authentication認(rèn)證實現(xiàn)方法
- Asp.net Core中實現(xiàn)自定義身份認(rèn)證的示例代碼
- 淺談ASP.NET Core 中jwt授權(quán)認(rèn)證的流程原理
- ASP.Net Core3.0中使用JWT認(rèn)證的實現(xiàn)
- Asp.Net Core基于JWT認(rèn)證的數(shù)據(jù)接口網(wǎng)關(guān)實例代碼
- ASP.NET學(xué)習(xí)CORE中使用Cookie身份認(rèn)證方法
- Asp.Net Core添加請求頭自定義認(rèn)證的示例
相關(guān)文章
sqlserver 刪除重復(fù)記錄處理(轉(zhuǎn))
刪除重復(fù)記錄有大小關(guān)系時,保留大或小其中一個記錄2011-07-07
win10下vs2015配置Opencv3.1.0詳細(xì)過程
這篇文章主要為大家詳細(xì)介紹了win10下vs2015配置Opencv3.1.0的詳細(xì)過程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11
asp.net 讀取文本文件并插入數(shù)據(jù)庫的實現(xiàn)代碼
最近我司和招行有合作,招行給財務(wù)的是一個txt格式的賬務(wù)文本文件,文本文件包含很多內(nèi)容,對賬只需要用到其中一部分內(nèi)容。2010-04-04
ASP.NET Core自定義中間件如何讀取Request.Body與Response.Body的內(nèi)容詳解
這篇文章主要給大家介紹了關(guān)于在ASP.NET Core自定義中間件中如何讀取Request.Body與Response.Body的內(nèi)容,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用ASP.NET Core具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
Equals和==的區(qū)別 公共變量和屬性的區(qū)別小結(jié)
Equals 和==的區(qū)別 公共變量和屬性的區(qū)別 總結(jié)一下。2009-11-11
.NET?ORM框架SqlSugar實現(xiàn)導(dǎo)航查詢功能
今天這篇文章分享一款好用簡單的ORM框架?SqlSugar,相比?EF?Core的導(dǎo)航查詢更加簡單,配置更加容易,幾分鐘就能上手,對.NET?ORM框架SqlSugar實現(xiàn)導(dǎo)航查詢功能感興趣的朋友一起看看吧2022-04-04

