中仑建设网站,潍坊网站建设自助建站平台,触动网站建设,微商城系统哪家强如果你没接触过旧版Asp.Net Mvc中的 Authorize 或者 Cookie登陆#xff0c;那么你一定会疑惑 认证这个名词#xff0c;这太正式了#xff0c;这到底代表这什么#xff1f;获取资源之前得先过两道关卡Authentication Authorization要想了解Identity中用户登录之后那么你一定会疑惑 认证这个名词这太正式了这到底代表这什么获取资源之前得先过两道关卡Authentication Authorization要想了解Identity中用户登录之后后续的访问时怎样识别用户的那首先我们得了解下认证Authentication 和授权Authorization的含义 游侠索罗星球大战外传 主演阿尔登·埃伦瑞奇 / 艾米莉亚·克拉克 / 唐纳德·格洛沃 猫眼电影演出 广告 购买 AuthenticationAuthentication就是认证的意思还举之前公园的例子我们拿到门票之后去公园入口门卫A首先要根据门票确认我们是谁是老王还是老赵门票是不是真的过期没。这个过程这个识别来访者是谁的过程就叫做Authentication身份认证过程那Authorization 又是啥这两个单词太像了甚至他们的释义都很像以至于我们在不了解他们的时候总是弄混他们Authorization是授权的意思上一小节中门卫A识别出了我们是谁Ok我们是老李那么门卫B能不能让我们进园呢不一定门卫B还要再看门票过期没上一步已经看过门票是否过期了为什么还要看呢事情是这样的门卫A看到门票过期了然后在门票副卡上写上“门票过期”四个大字再写上“认证失败”但是负责认证的门卫A没有拦着我们而是继续让我们前进因为动物园可能因为活动而允许过期门票进入或者没有门票也可以那么接下来授权的人门卫B来看门票他根据动物园切实的情况看看看许可范围再问问后台这个人是不是动物园的管理员。经过种种校验发现虽然门票过期了但是今天是开放日没门票也行但是我们是普通游客却来到了管理员通道所以没让我们进园——授权失败小结好了这就是认证和授权Authentication Authorization两个不同的事由两个不同的人或者组件来做认证用来确认来者是谁确认身份确认之后可能没有身份授权用来确认持有此身份的来者能不能访问当前请求的资源现在我们要记住认证与授权中的一个要点认证只确定用户是谁即使认证失败也不会拦截用户访问拦截用户访问发生在授权阶段另外要注意的是 Authentication和Authorization并不属于Identity的一部分都不属于Identity它和Identity是相互独立的然后一起协作。也就是说即便我们没有使用Identity 我们有我们自己的用户存储角色等等和身份权限相关的一切那么我们可以将我们的成员系统完美的与Asp.Net Core 进行集成我们可以假设Identity就是我们写的然后将其与Asp.Net Core进行集成那么为什么要将这个与Identity无关的认证过程Authentication放在这里呢因为它们是协作的 Authentication和Authorization本事就是要与成员系统协作的在代码上他们解耦并且独立但是在事实逻辑上成员系统和认证授权总是一起使用的所以一起讲容易理解那么这篇文章只讲 Authentication与Authorization中的第一个 —— Authentication先来了解一下asp.net core 是怎样知道我们已经登陆的访客是谁的身份认证中间件 Authentication Middleware中间件Middleware讲起来又是一个长长的故事如果你完全没概念那么我建议你先简单学习一下asp.net core 中的中间件你只要知道它的运行原理即可在一般的asp.net core web 项目中我们一般把身份认证中间件放在 静态文件中间件之后Mvc中间件之前public void Configure(IApplicationBuilder app, IHostingEnvironment env){ app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes { //略... }); }这样做的目的很简单仅对需要认证的部分做认证在http请求到达 mvc中间件之前也就是进入我们写的逻辑代码之前身份认证就结束了也就是说身份认证不能在 controller action中控制我们用一张图来简化发生在身份认证中间件中的认证过程注意这里马上要引入一个新的概念身份认证 handler中间件是嵌在中间件管道中的一个一个模块http请求有条件的流经他们另一个相似的东西有很多 handler 嵌在身份认证中间件上那么http是流经所有的handler吗Authentication HandlerAuthentication Hander 顾名思义他就是切实处理身份认证的组件它附加在 authentication middleware 上在请求到来时 middleware 会在所有附加在它之上的handler中选取一个用来做身份认证那么当我们使用Identity时哪些 authentication handler 被附加了呢当请求到来时authentication middleware 如何知道要选择哪个handler呢接下来我们一一解答Cookie Authentication HandlerIdentity只添加了一种类型的 handler ——CookieAuthenticationHandler在我们的StartUp类中的ConfigureServices方法中我们添加了Identity的Serviceservices.AddIdentityApplicationUser, IdentityRole() .AddEntityFrameworkStoresApplicationDbContext() .AddDefaultTokenProviders();但事情没这么简单在添加Identity的同时Identity还未我们的项目添加了AuthenticationService和CookieAuthenticationHandlerpublic static IdentityBuilder AddIdentityTUser, TRole( { // Services used by identity services.AddAuthentication(options { options.DefaultAuthenticateScheme IdentityConstants.ApplicationScheme; // 略... }) .AddCookie(IdentityConstants.ApplicationScheme, o { // 略... 在services.AddAuthentication的内部添加了AuthenticationServicenamespace Microsoft.Extensions.DependencyInjection{ public static class AuthenticationCoreServiceCollectionExtensions { public static IServiceCollection AddAuthenticationCore(this IServiceCollection services) { services.TryAddScopedIAuthenticationService, AuthenticationService(); services.TryAddScopedIAuthenticationHandlerProvider, AuthenticationHandlerProvider(); services.TryAddSingletonIAuthenticationSchemeProvider, AuthenticationSchemeProvider();注意上面代码的最后三行后面涉及到他们的获取他们就是在此处添加的namespace Microsoft.Extensions.DependencyInjection{ public static class CookieExtensions { public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme, string displayName, ActionCookieAuthenticationOptions configureOptions) { builder.Services.TryAddEnumerable(ServiceDescriptor.SingletonIPostConfigureOptionsCookieAuthenticationOptions, PostConfigureCookieAuthenticationOptions()); return builder.AddSchemeCookieAuthenticationOptions, CookieAuthenticationHandler(authenticationScheme, displayName, configureOptions);上方的代码添加了 CookieAuthenticationHandler在添加Authentication service的同时制定默认的 authentication scheme这个概念在之前的文章中提到过如果你还有印象的话 是谁(就是下方的cookie authentication handler)这时候另一个问题浮现了只添加了一个 cookie authentication handler为什么还要将他制定成默认值是否有有点多此一举呢?虽然Identity只添加了一种类型的 handlercookie authentication handler但是他同时添加了多个在 authentication 中间件上区分各个handler的方法是指定不同的 authentication scheme而不是通过 handler 的类型其实它添加了这么多services.AddAuthentication(options { options.DefaultAuthenticateScheme IdentityConstants.ApplicationScheme; options.DefaultChallengeScheme IdentityConstants.ApplicationScheme; options.DefaultSignInScheme IdentityConstants.ExternalScheme;}).AddCookie(IdentityConstants.ApplicationScheme, 略).AddCookie(IdentityConstants.ExternalScheme, 略).AddCookie(IdentityConstants.TwoFactorRememberMeScheme, 略).AddCookie(IdentityConstants.TwoFactorUserIdScheme,略);不过我们暂时不用关心这些是什么目前为止我们已经知道了这样几件事添加Identity时Identity添加了用于身份认证的服务以及默认激活的用于认证的handler——CookieAuthenticationHandlerIdentity的身份认证基于cookie 上篇文章我们了解到 Identity在登陆时将票据加密写入了cookie所以用户登录后再次访问的时候会通过cookie来识别当前用户是谁动手实践这一小节中我们先编写测试代码来看看认证过程产生了哪些结果创建一个名为TestAuthController的控制器代码大致如下namespace IdentityInAction.Controllers{ public class TestAuthController : Controller { public IActionResult Index() { return Json(new { User.Identity.IsAuthenticated, User.Identity.AuthenticationType, ClaimsUser.Claims.Select(c new { c.Type, c.Value }) // 略...这些代码将返回一个json字符串内容是 authentication的部分结果和用户的claims信息这三行核心代码的意思分别是用户是否已经通过身份认证对次请求进行认证的handler的名称在上篇文章中我们有提到 authentication scheme 就是 authentication type的另一个名字记住这件事对我们的理解很有帮助这个用户的Claims信息运行程序不要进行登陆如果已经登陆了则退出登陆退出登陆的链接是右上角的LogOut然后访问http://localhost:{你的端口}/testauth/index得到的结果如下{ isAuthenticated: false, authenticationType: null, claims: [] }由于没有用户登陆所以结果里几乎什么都没有然后再尝试登陆后再次访问这个地址结果如下{ isAuthenticated: true, authenticationType: Identity.Application, claims: [ { type: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier, value: 78a032c7-0d67-4cec-b031-2d15a7bac755 }, { type: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name, value: abcabc.com }, { type: AspNet.Identity.SecurityStamp, value: babbb46b-6ba0-4b87-875a-92088197dfbf } ]}isAuthenticated: true 这代表认证成功authenticationType: Identity.Application这是对该请求进行认证的handler的名字由前文我们知道我们默认的handler是名为IdentityConstants.ApplicationScheme的cookie handler我们看一小段源代码证实一下public class IdentityConstants{ private static readonly string CookiePrefix Identity; public static readonly string ApplicationScheme CookiePrefix .Application;正如所料接下来就是claims了再上篇文章中提到再登陆过程中加入到Identity的claims有这些UserName | http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifierUserId| http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameSecurityStamp如果支持的话| AspNet.Identity.SecurityStamp存储在数据库中的额外Claims如果支持的话注支持但当前用户没有这些claims随着票据一起加密写到了cookie中现在他们又随着cookie一起传了回来要注意的是即便我们退出登陆后没有身份认证失败了但是我们仍然获得了这个Uri的访问权限原因在于认证并不阻止用户授权才会阻止用户而我们没又做授权方面的限制看到这里我们的认证过程的大体已经清楚了接下来我们要看下整个认证过程的一点细节整个过程是自上而下的看标题为工作的那一列工作注释获取IAuthenticationHandlerProvider的实例获取默认的AuthenticationScheme使用上一步的scheme获取IAuthenticationService实例上一步的service通过第一步的IAuthenticationHandlerProvider获取handlerhandler 是 cookie authentication handlerhandler 调用 AuthenticateAsync这个方法最终调用了handler的HandleAuthenticateAsync①这个方法是事实上执行认证的方法获取 CookieAuthenticationOptions.Cookie.Name指定的存储票据的cookie的原始字符串这个Name的默认值是.AspNetCore.Identity.Application解密cookie字符串获得AuthenticationTicket的实例检查是否使用了session存储如果有则验证是否存在对应的session检查cookie 是否过期检查是否需要刷新cookie创建新的AuthenticationTicket将AuthenticationTicket中的Principal设置到HttpContext.User上,认证结束在动手做一节中我们使用的User就是在这个时候被赋值的需要注意① 谁进行的验证Identity的实现比较复杂兜兜转转最终的验证时由 cookie authentication handler 的 HandleAuthenticateAsync完成的如果你在看Identity源代码的话那么直接跳转到这里可以节省时间怎么验证的事实上说的简单一点就是在登陆的时候把票据加密写到cookie里验证的时候获取cookie 解密 还原成票据 把票据塞到http context中即使是认证失败了也是这4个步骤最终 负责授权的组件会检查 http context 中的票据还会结合其它情况来确定是否允许当前的请求继续进行下去而我们的逻辑代码中也可以查看票据根据不同的 认证结果 返回不同的数据相关文章 ASP.NET Core Identity 实战1——Identity 初次体验ASP.NET Core Identity Hands On2——注册、登录、Claim用 Identity Server 4 (JWKS 端点和 RS256 算法) 来保护 Python web api基于OIDCOpenID Connect的SSO学习Identity Server 4的预备知识使用Identity Server 4建立Authorization Server (1)使用Identity Server 4建立Authorization Server (2)使用Identity Server 4建立Authorization Server (3)使用Identity Server 4建立Authorization Server (4)使用Identity Server 4建立Authorization Server (5)IdentityServer410- 添加对外部认证的支持之QQ登录spring cloud.net core搭建微服务架构Api授权认证六原文地址: https://www.cnblogs.com/rocketRobin/p/9105720.html.NET社区新闻深度好文欢迎访问公众号文章汇总 http://www.csharpkit.com RocketRobin Reward 长按二维码向我转账 受苹果公司新规定影响微信 iOS 版的赞赏功能被关闭可通过二维码转账支持公众号。