Skip to main content

配置Asp.net Core Identity

分类:  Asp.net Core认证和授权 标签:  #Asp.Net core基础 #认证 #.Net 发布于: 2023-05-27 18:35:23

默认情况Identity使用默认的值对密码,Cookie, 声明进行配置,但是你可以在Startup.configureService中通过IdentityOptionIdentity进行配置,例如:

配置的方法如上图所示,但是必须要保证配置在调用AddIdentity或者AddDefaultIdentity之后。

 

声明标识(Claim Identity)配置

这里我们有必要理解一下ClaimClaim Identity这两个概念,Claim这里我们表示为声明,例如你进入公司的工牌,那么工牌就是我们的声明标识(Claim Identity), 但是工牌上的员工工号就是我们的声明(Claim),

通过IdentityOptionsClaimIdentiy来定义声明表示

 

属性

说明

默认值

RoleClaimType

设置角色的声明类型(RoleClaim)

ClaimType.Role

SecurityStampClaimType

设置安全标记声明的声明类型

AspNet.Identity.SecurityStamp

UserIdClaimType

设置用户声明标识的类型

ClaimTypes.NameIdentifier

UserNameClaimType

设置用户名的声明类型

ClaimTypes.Name

 

关于ClaimType的定义可以参考API文档:https://docs.microsoft.com/en-us/dotnet/api/system.security.claims.claimtypes?view=net-5.0

 

另外这里有几个概念比较难懂:Claim, ClaimIdentity, CliamPrincipal, 这里有一篇文章比较有参考意义:
https://www.cnblogs.com/liang24/p/13910368.html (ASP.NET Core Authentication系列(一)理解Claim, ClaimsIdentity,ClaimsPrincipal )

 

 

配置锁定(LockOut)
IdentityOptions.LockoutOptions

属性

说明

默认值

AllowedForNewUsers

确定新用户是否可以锁定。

true

DefaultLockoutTimeSpan

锁定发生时用户被锁定的时间长度。

AspNet.Identity.SecurityStamp

MaxFailedAccessAttempts

如果启用了锁定,则在用户被锁定之前失败的访问尝试次数。

 5

 

配置密码(Password)
IdentityOptions.PasswordOptions

属性

说明

默认值

RequireDigit

要求密码中的数字介于0-9 之间。

true

RequiredLength

密码的最小长度。

6

RequireLowercase

密码中需要小写字符。

true

RequireNonAlphanumeric

密码中需要一个非字母数字字符。

True

RequiredUniqueChars

需要密码中的非重复字符数。

1

RequireUppercase

密码中需要大写字符。

true

 

配置登录
Identitions.SignIn

属性

说明

默认值

RequireConfirmedEmail

需要确认电子邮件登录。

false

RequireConfirmedPhoneNumber

需要确认电话号码才能登录。

false

 

 

配置令牌

Identityopitons.TokenOptions:

配置用户


配置Cookie

可以参考文档:
 https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.authentication.cookies.cookieauthenticationoptions?view=aspnetcore-5.0

 配置密码hash