ASP.Net Core Identity是ASP.Net Core默认的内置的身份认证授权系统,可以管理成员,角色等等之类的东西,默认使用的是Microsoft SqlServer,然后,它也支持外部的身份认证。
• 写个小例子,学习记录一下:
一个控制器:AccountController;两个视图:Login和Register;两个模型类:LoginViewModel.cs和RegisterViewModel.cs
• ASP.Net Core Identity重点类:
UserManager<IdentityUser>:用来操作用户,比如:删除用户,添加用户....并把处理结果存储在一个地方,默认使用的SqlServer
SignInManager<IdentityUser>:主要用来对用户的身份认证的
• 代码示例:
新建一个AccountController控制器,并且注入以上两个重点类:
public class AccountController : Controller { private readonly SignInManager<IdentityUser> _signInManager; private readonly UserManager<IdentityUser> _userManager; public AccountController(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager) { _signInManager = signInManager; _userManager = userManager; } public IActionResult Login() { return View(); } [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); } public IActionResult Register() { return View(); } [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); } public async Task<IActionResult> logout() { await _signInManager.SignOutAsync(); return RedirectToAction("Index", "Home"); }
Login视图:
@model LoginViewModel <h2>请登录或者<a asp-action="Register" asp-controller="Account">注册</a></h2> <form asp-action="Login" asp-controller="Account" method="post"> <div> <label asp-for="UserName"></label> <input asp-for="UserName"/> <span asp-validation-for="UserName"></span> </div> <div> <label asp-for="Password"></label> <input asp-for="Password" /> <span asp-validation-for="Password"></span> </div> <div> <input type="submit" value="提交" /> </div> <div asp-validation-summary="All"></div> </form>
Register视图:
@model RegisterViewModel <h2>注册</h2> <form asp-action="Register" asp-controller="Account" method="post"> <div> <label asp-for="UserName"></label> <input asp-for="UserName" /> <span asp-validation-for="UserName"></span> </div> <div> <label asp-for="Password"></label> <input asp-for="Password" /> <span asp-validation-for="Password"></span> </div> <div> <input type="submit" value="提交" /> </div> <div asp-validation-summary="All"></div> </form>
Layout布局页:
<!DOCTYPE html> @using Microsoft.AspNetCore.Identity @inject SignInManager<IdentityUser> SignInManager <html> <head> <meta name="viewport" content="width=device-width" /> <title></title> <link href="~/node_modules/bootstrap/dist/css/bootstrap.css" rel="stylesheet" /> </head> <body> <nav class="navbar navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> @if (SignInManager.IsSignedIn(User)) { <form asp-action="Logout" asp-controller="Account" method="post" id="logoutForm"> <ul class="navbar-nav mr-auto"> <li> <a href="javascript:document.getElementById(‘logoutForm‘).submit()">登出</a> </li> </ul> </form> } else { <ul class="navbar-nav mr-auto"> <li> <a asp-action="Register" asp-controller="Account">注册</a> </li> <li> <a asp-action="Login" asp-controller="Account">登录</a> </li> </ul> } </nav> <div> @RenderBody() </div> <script src="~/node_modules/jquery/dist/jquery.js"></script> <script src="~/node_modules/jquery-validation/dist/jquery.validate.js"></script> <script src="~/node_modules/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive"></script> </body> </html>
LoginViewModel.cs和RegisterViewModel.cs内容一样,如下:
public class LoginViewModel { [Required] [Display(Name ="用户名")] public string UserName { get; set; } [Required] [Display(Name ="密码")] [DataType(DataType.Password)] public string Password { get; set; } }
最后,注册服务,进行数据迁移:
在startup.cs注册服务:
services.AddDbContext<IdentityDbContext>(options => options.UseMySql(_configuration.GetConnectionString("MysqlConnection"),b=>b.MigrationsAssembly("Tutorials.Web"))); services.AddDefaultIdentity<IdentityUser>().AddEntityFrameworkStores<IdentityDbContext>(); services.Configure<IdentityOptions>(options => { // Password settings. options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 1; options.Password.RequiredUniqueChars = 1; // Lockout settings. options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); options.Lockout.MaxFailedAccessAttempts = 5; options.Lockout.AllowedForNewUsers = false; // User settings. options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; options.User.RequireUniqueEmail = false; });
在Configure理添加:
app.UseAuthentication();
然后进行迁移,打开Nuget包控制台,首先输入迁移命令:
Add-migration initialIdentity -Context IdentityDbContext
然后输入更新数据库命令:
update database -Context IdentityDbContext
这个时候,数据库中会多几张表,用户存放用户信息。这样,一个小demo就实现了,用户登录,注册,登录成功或者注册成功后跳转到index页,并隐藏登录和注册按钮,显示登出按钮。