ASP.NET Core 身份验证概述

2/23/2022 7:14:52 PM
547
0

身份认证  https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/?view=aspnetcore-6.0

使用特定的方案   https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-6.0

 

 

  1. 在Startup类中的ConfigureServices方法通过添加AddAuthentication注册我们最主要的三个对象AuthenticationService, AuthenticationHandlerProvider, AuthenticationSchemeProvider
  2. 通过AddAuthentication返回的AuthenticationBuilder 通过AddJwtBearer(或者AddCookie)来指定Scheme类型和需要验证的参数
  3. 在Startup类中的Configure方法通过添加UseAuthentication注册认证中间件
  4. 在认证过程中,通过AuthenticationSchemeProvider获取正确的Scheme,在AuthenticationService中通过Scheme和AuthenticationHandlerProvider获取正确的AuthenticationHandler,最后通过对应的AuthenticationHandler的AuthenticateAsync方法进行认证流程

     https://cloud.tencent.com/developer/article/1498055

 

 

三、基于声明授权

对于上例来说,本质上也是基于声明(Claim)的授权,因为张三的"TestPutBookRole"角色也是作为一个Claim添加到证书中的。只不过采用了特定的ClaimTypes.Role。那么是否可以将其他的普通Claim作为授权的依据呢?当然是可以的。

这里涉及到了另一个单词“Policy”,翻译为策略?也就是说,可以把一系列的规则(例如要求姓名为李四,账号为002,国籍为中国等等)组合在一起,形成一个Policy,只有满足这个Policy的才可以被授权访问。

下面我们就新建一个Policy,在Startup的ConfigureServices中添加授权代码:

 

services.AddAuthorization(options=>options.AddPolicy("Name",policy=> {
   policy.RequireClaim(ClaimTypes.Name, "张三");
   policy.RequireClaim(ClaimTypes.NameIdentifier,"001");
}));

 

全部评论



提问