AspNet Core中的標識Identity,是用於Web應用程序的成員身份驗證系統。
最方便的引入辦法是在創建MVC或Pages的Web應用時,直接選擇相應的身份驗證系統。
如圖:
如果選擇的是“個人用戶帳戶”,則系統將包含7個實體類型,分別為User(用戶)、Role(角色)、UserClaim(用戶權限聲明)、UserToken(用戶身份驗證令牌)、RoleClaim(角色內所有用戶授予權限聲明)、UserLogin(用戶與登錄名關聯)、UserRole(用戶與角色關聯)。如何缺省的話,會對應創建如下7張數據表:
如果希望用戶身份驗證系統與自己使用的數據表結合在同一數據庫,則只需要你的數據上下文定義類繼承自IdentityDbContext(包含角色)即可。如
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { } public DbSet<Product> Products { get; set; } ... }
其中ApplicationUser是繼承自IdentityUser的自定義用戶類,該類可以添加一些自己的用戶屬性。如ClientIP、CreateDate等。如果不需要引入這些額外屬性,可以直接使用IdentityUser作為基類泛型。
OnModelCreating方法可以自定義數據表字段屬性。如字長、表名等。
這樣,最后生成的數據庫就可以直接包含你自己的表和身份驗證所需的7張表了,用起來比較方便。
對於MVC Web應用,使用身份驗證系統是挺簡單的。通過在Startup.cs文件進入依賴項注入:
(1)在ConfigureSerivces方法中添加:
services.AddDbContext<ApplicationDbContext>(options => options.UseMySql( Configuration.GetConnectionString("MysqlConnection")));
實現數據庫的訪問。
(2)在同一方法中添加
services.AddDefaultIdentity<ApplicationUser>() .AddRoles<IdentityRole>() .AddRoleManager<RoleManager<IdentityRole>>() .AddDefaultUI(UIFramework.Bootstrap4) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders();
注入用戶驗證服務。
(3)在Configure方法中添加
app.UseAuthentication();
添加授權服務。
(4)在控制器中引入如下命名空間(如果缺少對應的包,就通過NuGet安裝):
using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Authorization;
(5)使用相應的管理服務
public class ProductController : Controller { private readonly UserManager<ApplicationUser> _userManager; // 用戶管理 private readonly RoleManager<IdentityRole> _roleManager; // 角色管理 private readonly SignInManager<ApplicationUser> _signInManager; // 登錄管理 public ProductController(UserManager<Application> userManager, RoleManager<IdentityRole>, SignInManager<Applicationuser> signInManager) { _userManager = userManager; _roleManager = roleManager; _signInManager = signInManager; } ... }
此后,就可以使用上述字段變量調用相應的功能進行用戶管理了。