ASP.NET Core Identity
- 身份认证和授权系统
- 成员管理
- 默认使用 MSSQL
- 支持外部的 Provider
ASP.NET Core Identity 重点类
- UserManager<IdentityUser>:用户管理
- SignInManager<IdentityUser>:身份认证
public void ConfigureServices(IServiceCollection services)
{
...
// 注册 IdentityDbContext
services.AddDbContext<IdentityDbContext>(options =>
options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"),
b => b.MigrationsAssembly("Tutorial.Web")));
// 注册 Identity 服务
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<IdentityDbContext>();
// 配置 Identity
services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = false; //需要数值
options.Password.RequireLowercase = false;//需要小写字母
options.Password.RequireNonAlphanumeric = false;//需要非数值类型
options.Password.RequireUppercase = true; // 需要大写
options.Password.RequiredLength = 6; //长度
options.Password.RequiredUniqueChars = 1;//唯一字符
});
}
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILogger<Startup> logger)
{
...
app.UseAuthentication();
app.UseMvc(builder =>
{
builder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}");
});
}
注册:
[HttpPost] public async Task<IActionResult> Register(RegisterViewModel registerViewModel) { if (ModelState.IsValid) { var user = new IdentityUser { UserName = registerViewModel.UserName }; var result = await _userManager.CreateAsync(user, registerViewModel.PassWord); if (result.Succeeded) { return RedirectToAction("Index", "Home"); } return View(registerViewModel); } return View(registerViewModel); }
通过 Authorize 特性,限定只有登录用户才能添加学生:
[Authorize] [HttpGet] public IActionResult Create() { return View(); }
更多用法请参考https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/identity?view=aspnetcore-3.1&tabs=visual-studio