ASP.NET Core Identity
- 身份认证和授权系统
- 成员管理
- 默认使用 MSSQL
-
使用 ASP.NET Core Identity
登录和注册的 View
- AccountController
-
ASP.NET Core Identity 重点类
UserManager
:用户管理 - SignInManager
:身份认证 Identity 的具体使用
官方教程:Introduction to Identity
注册 Identity 服务并启用 Authority:
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;
...
});
}
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);
}
登录:
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel loginViewModel)
{
if (!ModelState.IsValid)
{
return View(loginViewModel);
}
var user = await _userManager.FindByNameAsync(loginViewModel.UserName);
if (user != null)
{
var result = await _signInManager
.PasswordSignInAsync(user, loginViewModel.PassWord, false, false);
if (result.Succeeded)
{
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "用户名/密码错误");
return View(loginViewModel);
}
登出:
[HttpPost]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return RedirectToAction("Index", "Home");
}
通过 Authorize 特性,限定只有登录用户才能添加学生:
[Authorize]
[HttpGet]
public IActionResult Create()
{
return View();
}