// 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认证协议中的浏览器行为
That's All . BA认证是随处可见的基础认证协议,本文期待以最清晰的方式帮助你理解协议:
实现了基本认证协议服务端,客户端;
到此这篇关于ASP.NET Core 实现基本认证的示例代码的文章就介绍到这了,更多相关ASP.NET Core基本认证内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章: