" 显示名jwtToken " ); 4 authenticationOptions.DefaultAuthentic
标签:
注册处事、配置选项、添加身份验证方案在Startup.ConfigureServices执行services.AddAuthentication()
注册如下处事(便于理解省略了部分帮助处事):
services.TryAddScoped<IAuthenticationService, AuthenticationService>();
services.TryAddScoped<IAuthenticationHandlerProvider, AuthenticationHandlerProvider>();
services.TryAddSingleton<IAuthenticationSchemeProvider, AuthenticationSchemeProvider>();
整个应用的身份验证有个选项东西叫AuthenticationOptions(上一篇有描述),允许我们对身份验证做整体配置,这个配置主要浮现为:配置系统需要撑持的身份验证方案列表;指定默认身份验证方案、默认登录时用的身份验证方案...默认注销...等。这个东西的应用使用asp.net core的选项模型,,我们可以通过AddAuthentication(Action<AuthenticationOptions>)重载来进行配置。参考如下代码:
1 services.AddAuthentication(authenticationOptions=> { 2 authenticationOptions.AddScheme<CookieAuthenticationHandler>("cookie", "显示名cookie"); 3 authenticationOptions.AddScheme<JwtBearerHandler>("jwt","显示名jwtToken"); 4 authenticationOptions.DefaultAuthenticateScheme = "cookie"; 5 //...其它配置 6 });
此重载同样会先注册上面的核心处事。然后设置初始化AuthenticationOptions的委托,当某个类注入AuthenticationOptions时,依赖注入框架会挪用此委托来初始化这个选项东西。
另一个重载AddAuthentication(string defaultAuthenticateScheme)内部也是挪用上面的要领,只是只设置了AuthenticationOptions.DefaultAuthenticateScheme
AddAuthentication要领始终返回AuthenticationBuilder,它允许我们通过链式挪用方法来向AuthenticationOptions添加多个身份验证方案,所以更常见的方法如下:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie().AddJwtBearer();
CookieAuthenticationDefaults.AuthenticationScheme常来指明将哪个身份验证方案作为默认。后续分袂添加了cookie和JwtBearer两个身份验证方案。
我们说AuthenticationOptions是针对整个应用措施的身份验证选项,可以简单理解为它是身份验证方案的配置时容器。针对特定身份验证方案也有本身的配置东西。以AddCookie()为例,它等同于:
1 authenticationOptions.AddScheme<CookieAuthenticationHandler>(CookieAuthenticationDefaults.AuthenticationScheme, "显示名cookie",); 2 service.Configre<CookieAuthenticationOptions>(options=>{ 4 options.Cookie.Name = CookieAuthenticationDefaults.CookiePrefix + name; 6 options.CookieManager = new ChunkingCookieManager(); 7 options.LoginPath = CookieAuthenticationDefaults.LoginPath; 8 options.LogoutPath = CookieAuthenticationDefaults.LogoutPath; 9 options.AccessDeniedPath = CookieAuthenticationDefaults.AccessDeniedPath; 10 } 11 });
CookieAuthenticationOptions就是针对这个cookie身份验证方案的选项东西,将来某个类注入此选项东西时,依赖注入框架会回调此委托来初始化它。参考:选项模型。固然AddCookie有对应的重载允许我们本身的委托来初始化这个选项东西。类似下面的代码:
1 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie("换个方案名","显示名",opt=> { 2 opt.SlidingExpiration = true;//滑动过期? 3 //设置其它跟cookie身份验证相关的东东... 4 }).AddJwtBearer();
此刻看看这段代码就亲切多了。
插入身份验证中间件上面只是注册了身份验证过程中需要的处事并配置了应用需要撑持身份验证方案列表,在将来请求抵达时需要一其中间件来措置惩罚惩罚身份验证,核心任务是找到默认身份验证措置惩罚惩罚器,通过它从请求中获恰当前用户标识,然后设置到httpContext.User属性上,至于措置惩罚惩罚的具体过程将不才一篇基于cookie的身份验证整体流程详细说。在Startup.Configre中通过扩展要领注册:
app.UseRouting();
app.UseAuthentication();
app.UseEndpoints(endpoints =>{
endpoints.MapRazorPages();
});
至于为啥身份验证中间件必然要在 app.UseRouting(); 之后,我是真的想欠亨....
asp.net core 3.x 身份验证-2启动阶段的配置
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30226.html