feat:更新

main
bicijinlian 2 years ago
parent b86af6f7b8
commit eb5e59fec0

@ -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<BrowserAuthenticationBaseHandler>(AuthenticationSchemeName, AuthenticationDispalyName);
options.DefaultScheme = authenticationSchemeName;
options.DefaultAuthenticateScheme = authenticationSchemeName;
options.DefaultChallengeScheme = authenticationSchemeName;
options.DefaultForbidScheme = authenticationSchemeName;
options.DefaultSignInScheme = authenticationSchemeName;
options.DefaultSignOutScheme = authenticationSchemeName;
options.AddScheme<BrowserAuthenticationBaseHandler>(authenticationSchemeName, authenticationDisplayName);
});
return builder;

@ -22,7 +22,6 @@ namespace AuthStudy.Authentication.Browser
/// </summary>
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);

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

@ -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<AccountsController> _logger;
private readonly ILogger<AccountsController> _logger;
public AccountsController(ILogger<AccountsController> 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<IActionResult> GetAll()
{
// var authenticateResult = await HttpContext.AuthenticateAsync();
// if (authenticateResult.Succeeded)
@ -53,13 +52,67 @@ namespace AuthStudy.WebApp.Controllers
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);
}
[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]
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);
}

@ -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<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" };
})
@ -60,17 +76,38 @@ namespace AuthStudy.WebApp
};
})
;
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
;*/
//默认基类实现注册
#endregion
#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 =>
{
configure.DefaultPolicy = policy;
configure.InvokeHandlersAfterFailure = true;
configure.AddPolicy("DefaultPolicy",policy);
});
#endregion
WebApplication app = builder.Build();

Loading…
Cancel
Save