描述
asp.net Core Identity提供給我們一組工具包和API,能幫助我們應(yīng)用程序創(chuàng)建授權(quán)和認(rèn)證功能。也可以用它創(chuàng)建賬戶并使用用戶名和密碼進(jìn)行登錄,同時(shí)也提供了角色和角色管理功能。
1.創(chuàng)建項(xiàng)目
- 配置項(xiàng)
- nuget包
- Microsoft.AspNetCore.Identity.EntityFrameWorkCore
- Microsoft.EntityFrameworkCore.Design
- Microsoft.EntityFrameworkCore.SqlServer
- nuget包
- 配置項(xiàng)目
Program.cs
app.UseAuthorization();
app.UseAuthorization();
-
設(shè)置Asp.net Core Identity
User類
User類繼承IdentityUser類,位于Microsoft.AspNetCore.Identity中 在Models文件夾中穿件AppUser類 IdentityUser類中提供了一些用戶屬性,如:用戶名、電子郵件、電話、密碼hash值等。 如果IdentityUser類不能滿足要求,可以在AppUser中添加自定義的屬性
IdentityUser常用屬性
名稱 | 描述 |
---|---|
ID | 用戶唯一ID |
UserName | 用戶名稱 |
用戶Email | |
PasswordHash | 用戶密碼Hash的值 |
PhoneNumber | 用戶電話號碼 |
SecurityStamp | 當(dāng)每次用戶的數(shù)據(jù)修改時(shí)生成隨機(jī)值 |
創(chuàng)建Database Context
DataBase Context類繼承IdentityDbContext<T>類,T表示User類,在應(yīng)用程序中使用AppUser,IdentityDbContext通過使用EntityFrameworkCore和數(shù)據(jù)庫進(jìn)行交互
AppIdentyDbContext繼承IdentityDbContext
namespace IdentityDemo1.Models
{
public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options) : base(options)
{
}
}
}
創(chuàng)建數(shù)據(jù)庫字符串連接
appsettings.json中配置文章來源:http://www.zghlxwxcb.cn/news/detail-586164.html
appsettings.json中配置數(shù)據(jù)庫連接字符串
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"Default": "Data Source=.;Initial Catalog=IdentityDemo;Integrated Security=True;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=true"
},
"AllowedHosts": "*"
}
點(diǎn)擊查看代碼
builder.Services.AddDbContext<AppIdentityDbContext>(opt =>
{
opt.UseSqlServer(builder.Configuration["ConnectionStrings:Default"]);
});
添加Asp.Net Identity服務(wù)
添加Asp.Net Identity服務(wù)
builder.Services.AddIdentity<AppUser, IdentityRole>()
.AddEntityFrameworkStores<AppIdentityDbContext>()
.AddDefaultTokenProviders();
使用EF Migration命令創(chuàng)建Identity數(shù)據(jù)庫
nuget命令
nuget EntityFrameworkCore.Tool
Add-Migration InitCreateDB
update-database
執(zhí)行后的結(jié)果是
包含用戶記錄,角色,Claims,token 和登錄次數(shù)詳細(xì)信息等。文章來源地址http://www.zghlxwxcb.cn/news/detail-586164.html
- __EFMigrationsHistory:包含了前面所有的Migration
- AspNetRoleClaims :按角色存儲Claims
- AspNetRoles:存儲所有角色
- AspNetUserClaims :存儲用戶的Claims
- AspNetUserLogins :存儲用戶的登錄次數(shù)
- AspNetUserRoles: 存儲用戶的對應(yīng)的角色
- AspNetUsers:存儲用戶
- AspNetUserTokens 存儲外部認(rèn)證的token
到了這里,關(guān)于netcore Identity(一)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!