feat:更新

main
bicijinlian 2 years ago
parent b86af6f7b8
commit eb5e59fec0

@ -10,15 +10,15 @@ using Microsoft.Extensions.DependencyInjection;
namespace AuthStudy.Authentication.Browser namespace AuthStudy.Authentication.Browser
{ {
public static class BrowserAuthenticationExtensions public static class BaseBrowserAuthenticationExtensions
{ {
#region 基于接口的扩展注册 #region 基于接口的扩展注册
public static IServiceCollection AddBrowserAuthentication public static IServiceCollection AddBaseBrowserAuthentication
( (
this IServiceCollection builder, this IServiceCollection builder,
string AuthenticationSchemeName, string authenticationSchemeName,
string AuthenticationDispalyName, string authenticationDisplayName,
BrowserAuthenticationOptions Option BrowserAuthenticationOptions authenticationOption
) )
{ {
if (builder == null) if (builder == null)
@ -26,18 +26,18 @@ namespace AuthStudy.Authentication.Browser
throw new ArgumentNullException(nameof(builder)); throw new ArgumentNullException(nameof(builder));
} }
builder.AddService(Option); builder.AddService(authenticationOption);
builder.AddAuthentication(options => builder.AddAuthentication(options =>
{ {
options.DefaultScheme = AuthenticationSchemeName; options.DefaultScheme = authenticationSchemeName;
options.DefaultAuthenticateScheme = AuthenticationSchemeName; options.DefaultAuthenticateScheme = authenticationSchemeName;
options.DefaultChallengeScheme = AuthenticationSchemeName; options.DefaultChallengeScheme = authenticationSchemeName;
options.DefaultForbidScheme = AuthenticationSchemeName; options.DefaultForbidScheme = authenticationSchemeName;
options.DefaultSignInScheme = AuthenticationSchemeName; options.DefaultSignInScheme = authenticationSchemeName;
options.DefaultSignOutScheme = AuthenticationSchemeName; options.DefaultSignOutScheme = authenticationSchemeName;
options.AddScheme<BrowserAuthenticationBaseHandler>(AuthenticationSchemeName, AuthenticationDispalyName); options.AddScheme<BrowserAuthenticationBaseHandler>(authenticationSchemeName, authenticationDisplayName);
}); });
return builder; return builder;

@ -22,7 +22,6 @@ namespace AuthStudy.Authentication.Browser
/// </summary> /// </summary>
public class BrowserAuthenticationBaseHandler : public class BrowserAuthenticationBaseHandler :
IAuthenticationHandler, IAuthenticationHandler,
IAuthenticationRequestHandler,
IAuthenticationSignInHandler, IAuthenticationSignInHandler,
IAuthenticationSignOutHandler IAuthenticationSignOutHandler
{ {
@ -46,13 +45,13 @@ namespace AuthStudy.Authentication.Browser
//认证结果 //认证结果
AuthenticateResult result; AuthenticateResult result;
//属性 //认证属性
var properties = new AuthenticationProperties(); var properties = new AuthenticationProperties();
properties.Items.Add("AuthenticationBrowser", "浏览器认证属性"); properties.Items.Add("AuthenticationBrowser", "浏览器认证属性");
//获取请求浏览器信息,如果请头重复则以后面的为准 //获取请求浏览器信息,如果请头重复则以后面的为准
var userAgent = CurrentHttpContext?.Request.Headers["User-Agent"].LastOrDefault(); var userAgent = CurrentHttpContext?.Request.Headers["User-Agent"].ToString();
if (userAgent == null) if (string.IsNullOrWhiteSpace(userAgent))
{ {
properties.UpdateTokenValue("AuthenticationBrowser", "失败:获取不到浏览器信息"); properties.UpdateTokenValue("AuthenticationBrowser", "失败:获取不到浏览器信息");
result = AuthenticateResult.Fail($"失败:获取不到浏览器信息", properties); result = AuthenticateResult.Fail($"失败:获取不到浏览器信息", properties);

@ -4,7 +4,10 @@
{ {
public const string SchemeName = "BrowserScheme"; public const string SchemeName = "BrowserScheme";
public const string BaseSchemeName = "BaseBrowserScheme";
public const string DisplayName = "浏览器认证方案(基类实现方式)"; public const string DisplayName = "浏览器认证方案(基类实现方式)";
public const string BaseDisplayName = "Base浏览器认证方案(基类实现方式)";
public static List<string> AllowBrowsers { get; set; } = new() { "Chrome", "Edge", "Firefox" }; public static List<string> AllowBrowsers { get; set; } = new() { "Chrome", "Edge", "Firefox" };

@ -1,10 +1,9 @@
using AuthStudy.Authentication.Browser; using Microsoft.AspNetCore.Mvc;
using AuthStudy.WebApp.VModels; using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using AuthStudy.WebApp.VModels;
namespace AuthStudy.WebApp.Controllers namespace AuthStudy.WebApp.Controllers
{ {
@ -12,13 +11,13 @@ namespace AuthStudy.WebApp.Controllers
[ApiController] [ApiController]
public class AccountsController : ControllerBase public class AccountsController : ControllerBase
{ {
private ILogger<AccountsController> _logger; private readonly ILogger<AccountsController> _logger;
public AccountsController(ILogger<AccountsController> logger) public AccountsController(ILogger<AccountsController> logger)
{ {
_logger = logger; _logger = logger;
} }
//多特性是and特性内逗号分隔是or //多特性是 and, 特性内逗号分隔是or
[Authorize] [Authorize]
//[Authorize(AuthenticationSchemes = AuthenticationSchemeList.BaseBrowserScheme)] //[Authorize(AuthenticationSchemes = AuthenticationSchemeList.BaseBrowserScheme)]
//[Authorize(AuthenticationSchemes = AuthenticationSchemeList.BrowserScheme)] //[Authorize(AuthenticationSchemes = AuthenticationSchemeList.BrowserScheme)]
@ -26,7 +25,7 @@ namespace AuthStudy.WebApp.Controllers
//[Authorize(AuthenticationSchemes = $"{AuthenticationSchemeList.BrowserScheme},{AuthenticationSchemeList.BasicScheme}")] //[Authorize(AuthenticationSchemes = $"{AuthenticationSchemeList.BrowserScheme},{AuthenticationSchemeList.BasicScheme}")]
//[Authorize(AuthenticationSchemes = $"{AuthenticationSchemeList.BaseBrowserScheme},{AuthenticationSchemeList.BrowserScheme},{AuthenticationSchemeList.BasicScheme}")] //[Authorize(AuthenticationSchemes = $"{AuthenticationSchemeList.BaseBrowserScheme},{AuthenticationSchemeList.BrowserScheme},{AuthenticationSchemeList.BasicScheme}")]
[HttpGet] [HttpGet]
public IActionResult GetAll() public async Task<IActionResult> GetAll()
{ {
// var authenticateResult = await HttpContext.AuthenticateAsync(); // var authenticateResult = await HttpContext.AuthenticateAsync();
// if (authenticateResult.Succeeded) // if (authenticateResult.Succeeded)
@ -53,13 +52,67 @@ namespace AuthStudy.WebApp.Controllers
new AccountVM(){ Name="癫子", Email="dianzi@qq.com", Password="123456"} new AccountVM(){ Name="癫子", Email="dianzi@qq.com", Password="123456"}
}; };
//授权
var authorazitionService = HttpContext.RequestServices.GetService<IAuthorizationService>();
Task<AuthorizationResult>? authResult = authorazitionService?.AuthorizeAsync(HttpContext.User, "DefaultPolicy");
var dd = await authResult;
return new JsonResult(accounts); return new JsonResult(accounts);
} }
[Authorize(
AuthenticationSchemes = $"{AuthenticationSchemeList.BrowserScheme},{AuthenticationSchemeList.BaseBrowserScheme}",
Policy = "DefaultPolicy",
Roles = "Admin,User"
)]
[HttpGet]
public async Task<IActionResult> GetFirst()
{
var o = HttpContext.RequestServices.GetService<IOptions<AuthenticationOptions>>();
_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"} );
}
/// <summary>
/// 手动认证与授权
/// </summary>
[HttpGet]
public async Task<IActionResult> GetLast()
{
var o = HttpContext.RequestServices.GetService<IOptions<AuthenticationOptions>>();
_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] [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); return new JsonResult(info);
} }

@ -3,6 +3,10 @@ using AuthStudy.Authentication.Basic;
using AuthStudy.Authentication.Basic.Events; using AuthStudy.Authentication.Basic.Events;
using AuthStudy.Authentication.Browser; using AuthStudy.Authentication.Browser;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
namespace AuthStudy.WebApp namespace AuthStudy.WebApp
{ {
public class Program public class Program
@ -18,20 +22,32 @@ namespace AuthStudy.WebApp
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
#region 认证注册 #region 认证注册
//接口实现注册 //基于接口的浏览器认证
builder.Services.AddBrowserAuthentication builder.Services.AddBaseBrowserAuthentication
( (
BrowserAuthenticationDefault.SchemeName, BrowserAuthenticationDefault.BaseSchemeName,
BrowserAuthenticationDefault.DisplayName, BrowserAuthenticationDefault.BaseDisplayName,
new BrowserAuthenticationOptions() new BrowserAuthenticationOptions()
{ {
AllowBrowsers = new List<string>() { "Edge" } AllowBrowsers = new List<string>() { "Edge" }
} }
); )
builder.Services //基于基类的浏览器认证
.AddAuthentication(AuthenticationSchemeList.BaseBrowserScheme) .AddAuthentication(option =>
{
//此处的默认认证方案覆盖之前的设置
option.DefaultScheme = BrowserAuthenticationDefault.SchemeName;
option.DefaultAuthenticateScheme = BrowserAuthenticationDefault.SchemeName;
})
//浏览器认证
.AddScheme<BrowserAuthenticationOptions, BrowserAuthenticationHandler>(AuthenticationSchemeList.BrowserScheme, option =>
{
option.AllowBrowsers = new List<string>() { "Edge", "Chrome", "Firefox" };
});
/*builder.Services
.AddAuthentication(AuthenticationSchemeList.BrowserScheme)//认证基本服务注册
//浏览器认证 //浏览器认证
.AddScheme<BrowserAuthenticationOptions, BrowserAuthenticationHandler>(AuthenticationSchemeList.BaseBrowserScheme, option => .AddScheme<BrowserAuthenticationOptions, BrowserAuthenticationHandler>(AuthenticationSchemeList.BrowserScheme, option =>
{ {
option.AllowBrowsers = new List<string>() { "Edge", "Chrome", "Firefox" }; option.AllowBrowsers = new List<string>() { "Edge", "Chrome", "Firefox" };
}) })
@ -60,17 +76,38 @@ namespace AuthStudy.WebApp
}; };
}) })
; .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
;*/
//默认基类实现注册 //默认基类实现注册
#endregion #endregion
#region 授权注册 #region 授权注册
var policy = new AuthorizationPolicy
(
new[]
{
new AssertionRequirement(context =>
{
context.User.Claims.Any(i => i.GetType() == ClaimTypes.Name.GetType());
return true;
})
},
new List<string>()
{
//BrowserAuthenticationDefault.SchemeName, BasicAuthenticationDefaults.AuthenticationScheme
}
);
builder.Services.AddAuthorization(configure => builder.Services.AddAuthorization(configure =>
{ {
configure.DefaultPolicy = policy;
configure.InvokeHandlersAfterFailure = true;
configure.AddPolicy("DefaultPolicy",policy);
}); });
#endregion #endregion
WebApplication app = builder.Build(); WebApplication app = builder.Build();

Loading…
Cancel
Save