using System.Security.Claims; 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 { public static void Main(string[] args) { WebApplicationBuilder builder = WebApplication.CreateBuilder(args); // 添加服务到IoC容器 builder.Services.AddControllers(); //这里已经调用过了基础的认证与授权方法 // Swagger 注册 builder.Services.AddSwaggerGen(); #region 认证注册 //基于接口的浏览器认证 builder.Services.AddBaseBrowserAuthentication ( BrowserAuthenticationDefault.BaseSchemeName, BrowserAuthenticationDefault.BaseDisplayName, new BrowserAuthenticationOptions() { AllowBrowsers = new List() { "Edge" } } ) //基于基类的浏览器认证 .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.BrowserScheme, option => { option.AllowBrowsers = new List() { "Edge", "Chrome", "Firefox" }; }) //基本认证 .AddBasic(BasicAuthenticationDefaults.AuthenticationScheme,options => { options.Realm = "Basic Authentication"; options.Events = new BasicAuthenticationEvents { OnValidateCredentials = context => { if (context.Username == context.Password) { var claims = new[] { new Claim(ClaimTypes.NameIdentifier, context.Username??"", ClaimValueTypes.String, context.Options.ClaimsIssuer), new Claim(ClaimTypes.Name, context.Username??"", ClaimValueTypes.String, context.Options.ClaimsIssuer) }; context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name)); context.Success(); } return Task.CompletedTask; } }; }) .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() { //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(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run(); } } }