From eb5e59fec03757e450015e28b91136640a667139 Mon Sep 17 00:00:00 2001 From: bicijinlian Date: Mon, 26 Jun 2023 18:52:12 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...=> BaseBrowserAuthenticationExtensions.cs} | 28 +++---- .../BrowserAuthenticationBaseHandler.cs | 7 +- .../BrowserAuthenticationDefault.cs | 3 + .../Controllers/AccountsController.cs | 75 ++++++++++++++++--- AuthStudy.WebApp/Program.cs | 63 ++++++++++++---- 5 files changed, 134 insertions(+), 42 deletions(-) rename AuthStudy.Authentication.Browser/{BrowserAuthenticationExtensions.cs => BaseBrowserAuthenticationExtensions.cs} (61%) diff --git a/AuthStudy.Authentication.Browser/BrowserAuthenticationExtensions.cs b/AuthStudy.Authentication.Browser/BaseBrowserAuthenticationExtensions.cs similarity index 61% rename from AuthStudy.Authentication.Browser/BrowserAuthenticationExtensions.cs rename to AuthStudy.Authentication.Browser/BaseBrowserAuthenticationExtensions.cs index 85fafdd..cf48663 100644 --- a/AuthStudy.Authentication.Browser/BrowserAuthenticationExtensions.cs +++ b/AuthStudy.Authentication.Browser/BaseBrowserAuthenticationExtensions.cs @@ -10,15 +10,15 @@ using Microsoft.Extensions.DependencyInjection; namespace AuthStudy.Authentication.Browser { - public static class BrowserAuthenticationExtensions + public static class BaseBrowserAuthenticationExtensions { #region 基于接口的扩展注册 - public static IServiceCollection AddBrowserAuthentication + public static IServiceCollection AddBaseBrowserAuthentication ( this IServiceCollection builder, - string AuthenticationSchemeName, - string AuthenticationDispalyName, - BrowserAuthenticationOptions Option + string authenticationSchemeName, + string authenticationDisplayName, + BrowserAuthenticationOptions authenticationOption ) { if (builder == null) @@ -26,18 +26,18 @@ namespace AuthStudy.Authentication.Browser throw new ArgumentNullException(nameof(builder)); } - builder.AddService(Option); + builder.AddService(authenticationOption); builder.AddAuthentication(options => { - options.DefaultScheme = AuthenticationSchemeName; - options.DefaultAuthenticateScheme = AuthenticationSchemeName; - options.DefaultChallengeScheme = AuthenticationSchemeName; - options.DefaultForbidScheme = AuthenticationSchemeName; - options.DefaultSignInScheme = AuthenticationSchemeName; - options.DefaultSignOutScheme = AuthenticationSchemeName; - - options.AddScheme(AuthenticationSchemeName, AuthenticationDispalyName); + options.DefaultScheme = authenticationSchemeName; + options.DefaultAuthenticateScheme = authenticationSchemeName; + options.DefaultChallengeScheme = authenticationSchemeName; + options.DefaultForbidScheme = authenticationSchemeName; + options.DefaultSignInScheme = authenticationSchemeName; + options.DefaultSignOutScheme = authenticationSchemeName; + + options.AddScheme(authenticationSchemeName, authenticationDisplayName); }); return builder; diff --git a/AuthStudy.Authentication.Browser/BrowserAuthenticationBaseHandler.cs b/AuthStudy.Authentication.Browser/BrowserAuthenticationBaseHandler.cs index 29a0cb5..48a0ce2 100644 --- a/AuthStudy.Authentication.Browser/BrowserAuthenticationBaseHandler.cs +++ b/AuthStudy.Authentication.Browser/BrowserAuthenticationBaseHandler.cs @@ -22,7 +22,6 @@ namespace AuthStudy.Authentication.Browser /// public class BrowserAuthenticationBaseHandler : IAuthenticationHandler, - IAuthenticationRequestHandler, IAuthenticationSignInHandler, IAuthenticationSignOutHandler { @@ -46,13 +45,13 @@ namespace AuthStudy.Authentication.Browser //认证结果 AuthenticateResult result; - //属性 + //认证属性 var properties = new AuthenticationProperties(); properties.Items.Add("AuthenticationBrowser", "浏览器认证属性"); //获取请求浏览器信息,如果请头重复则以后面的为准 - var userAgent = CurrentHttpContext?.Request.Headers["User-Agent"].LastOrDefault(); - if (userAgent == null) + var userAgent = CurrentHttpContext?.Request.Headers["User-Agent"].ToString(); + if (string.IsNullOrWhiteSpace(userAgent)) { properties.UpdateTokenValue("AuthenticationBrowser", "失败:获取不到浏览器信息"); result = AuthenticateResult.Fail($"失败:获取不到浏览器信息", properties); diff --git a/AuthStudy.Authentication.Browser/BrowserAuthenticationDefault.cs b/AuthStudy.Authentication.Browser/BrowserAuthenticationDefault.cs index 4a8d294..a59dca5 100644 --- a/AuthStudy.Authentication.Browser/BrowserAuthenticationDefault.cs +++ b/AuthStudy.Authentication.Browser/BrowserAuthenticationDefault.cs @@ -3,8 +3,11 @@ public static class BrowserAuthenticationDefault { public const string SchemeName = "BrowserScheme"; + + public const string BaseSchemeName = "BaseBrowserScheme"; public const string DisplayName = "浏览器认证方案(基类实现方式)"; + public const string BaseDisplayName = "Base浏览器认证方案(基类实现方式)"; public static List AllowBrowsers { get; set; } = new() { "Chrome", "Edge", "Firefox" }; diff --git a/AuthStudy.WebApp/Controllers/AccountsController.cs b/AuthStudy.WebApp/Controllers/AccountsController.cs index 9fc80f2..618feb8 100644 --- a/AuthStudy.WebApp/Controllers/AccountsController.cs +++ b/AuthStudy.WebApp/Controllers/AccountsController.cs @@ -1,10 +1,9 @@ -using AuthStudy.Authentication.Browser; -using AuthStudy.WebApp.VModels; - +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; + +using AuthStudy.WebApp.VModels; namespace AuthStudy.WebApp.Controllers { @@ -12,13 +11,13 @@ namespace AuthStudy.WebApp.Controllers [ApiController] public class AccountsController : ControllerBase { - private ILogger _logger; + private readonly ILogger _logger; public AccountsController(ILogger logger) { _logger = logger; } - //多特性是and特性内逗号分隔是or + //多特性是 and, 特性内逗号分隔是or [Authorize] //[Authorize(AuthenticationSchemes = AuthenticationSchemeList.BaseBrowserScheme)] //[Authorize(AuthenticationSchemes = AuthenticationSchemeList.BrowserScheme)] @@ -26,7 +25,7 @@ namespace AuthStudy.WebApp.Controllers //[Authorize(AuthenticationSchemes = $"{AuthenticationSchemeList.BrowserScheme},{AuthenticationSchemeList.BasicScheme}")] //[Authorize(AuthenticationSchemes = $"{AuthenticationSchemeList.BaseBrowserScheme},{AuthenticationSchemeList.BrowserScheme},{AuthenticationSchemeList.BasicScheme}")] [HttpGet] - public IActionResult GetAll() + public async Task GetAll() { // var authenticateResult = await HttpContext.AuthenticateAsync(); // if (authenticateResult.Succeeded) @@ -52,14 +51,68 @@ namespace AuthStudy.WebApp.Controllers new AccountVM(){ Name="小明", Email="xiaoming@qq.com", Password="123456"}, new AccountVM(){ Name="癫子", Email="dianzi@qq.com", Password="123456"} }; - + + //授权 + var authorazitionService = HttpContext.RequestServices.GetService(); + Task? authResult = authorazitionService?.AuthorizeAsync(HttpContext.User, "DefaultPolicy"); + var dd = await authResult; return new JsonResult(accounts); } + + [Authorize( + AuthenticationSchemes = $"{AuthenticationSchemeList.BrowserScheme},{AuthenticationSchemeList.BaseBrowserScheme}", + Policy = "DefaultPolicy", + Roles = "Admin,User" + )] + [HttpGet] + public async Task GetFirst() + { + var o = HttpContext.RequestServices.GetService>(); + _logger.LogInformation($"默认全局认证方案:{o?.Value.DefaultScheme},当前默认方案{o?.Value.DefaultAuthenticateScheme}"); + var authenticateResult = await HttpContext.AuthenticateAsync(); + if (authenticateResult.Succeeded) + { + _logger.LogInformation("认证成功"); + } + else + { + Response.StatusCode = 401; + _logger.LogInformation("认证失败"); + return new ContentResult() { StatusCode = 401,Content=authenticateResult.Failure?.Message}; + } + + + return new JsonResult(new AccountVM(){ Name="张三", Email="zhangsan@qq.com", Password="123456"} ); + } + + /// + /// 手动认证与授权 + /// + [HttpGet] + public async Task GetLast() + { + var o = HttpContext.RequestServices.GetService>(); + _logger.LogInformation($"默认全局认证方案:{o?.Value.DefaultScheme},当前默认方案{o?.Value.DefaultAuthenticateScheme}"); + var authenticateResult = await HttpContext.AuthenticateAsync(); + if (authenticateResult.Succeeded) + { + _logger.LogInformation("认证成功"); + } + else + { + Response.StatusCode = 401; + _logger.LogInformation("认证失败"); + return new ContentResult() { StatusCode = 401,Content=authenticateResult.Failure?.Message}; + } + + + return new JsonResult(new AccountVM(){ Name="丁聪", Email="dingding@qq.com", Password="123456"} ); + } [HttpPost] - public IActionResult Login(string LoginName, string LoginPassword) + public IActionResult Login(string loginName, string loginPassword) { - var info = new { Name = LoginName, Roles = "Admin" }; + var info = new { Name = loginName, Roles = "Admin" }; return new JsonResult(info); } diff --git a/AuthStudy.WebApp/Program.cs b/AuthStudy.WebApp/Program.cs index f827a9e..f6b4a7b 100644 --- a/AuthStudy.WebApp/Program.cs +++ b/AuthStudy.WebApp/Program.cs @@ -3,6 +3,10 @@ using AuthStudy.Authentication.Basic; using AuthStudy.Authentication.Basic.Events; using AuthStudy.Authentication.Browser; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization.Infrastructure; + namespace AuthStudy.WebApp { public class Program @@ -18,20 +22,32 @@ namespace AuthStudy.WebApp builder.Services.AddSwaggerGen(); #region 认证注册 - //接口实现注册 - builder.Services.AddBrowserAuthentication + //基于接口的浏览器认证 + builder.Services.AddBaseBrowserAuthentication ( - BrowserAuthenticationDefault.SchemeName, - BrowserAuthenticationDefault.DisplayName, + BrowserAuthenticationDefault.BaseSchemeName, + BrowserAuthenticationDefault.BaseDisplayName, new BrowserAuthenticationOptions() { AllowBrowsers = new List() { "Edge" } } - ); - builder.Services - .AddAuthentication(AuthenticationSchemeList.BaseBrowserScheme) + ) + //基于基类的浏览器认证 + .AddAuthentication(option => + { + //此处的默认认证方案覆盖之前的设置 + option.DefaultScheme = BrowserAuthenticationDefault.SchemeName; + option.DefaultAuthenticateScheme = BrowserAuthenticationDefault.SchemeName; + }) + //浏览器认证 + .AddScheme(AuthenticationSchemeList.BrowserScheme, option => + { + option.AllowBrowsers = new List() { "Edge", "Chrome", "Firefox" }; + }); + /*builder.Services + .AddAuthentication(AuthenticationSchemeList.BrowserScheme)//认证基本服务注册 //浏览器认证 - .AddScheme(AuthenticationSchemeList.BaseBrowserScheme, option => + .AddScheme(AuthenticationSchemeList.BrowserScheme, option => { option.AllowBrowsers = new List() { "Edge", "Chrome", "Firefox" }; }) @@ -60,21 +76,42 @@ namespace AuthStudy.WebApp }; }) - ; + .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme) + ;*/ //默认基类实现注册 #endregion #region 授权注册 - builder.Services.AddAuthorization(configure => + + var policy = new AuthorizationPolicy + ( + new[] + { + new AssertionRequirement(context => + { + context.User.Claims.Any(i => i.GetType() == ClaimTypes.Name.GetType()); + return true; + }) + }, + new List() + { + //BrowserAuthenticationDefault.SchemeName, BasicAuthenticationDefaults.AuthenticationScheme + } + ); + builder.Services.AddAuthorization(configure => { - + configure.DefaultPolicy = policy; + configure.InvokeHandlersAfterFailure = true; + configure.AddPolicy("DefaultPolicy",policy); }); + + #endregion WebApplication app = builder.Build(); - + // 配置 Http 管道. app.UseSwagger(); app.UseSwaggerUI(); @@ -83,7 +120,7 @@ namespace AuthStudy.WebApp app.UseAuthorization(); app.MapControllers(); - + app.Run(); } }