Visual

14 ASP.NET Core Identity 入门.mp4 (116.36MB)

ASP.NET Core Identity

  • 身份认证和授权系统
  • 成员管理
  • 默认使用 MSSQL
  • 支持外部的 Provider

使用 ASP.NET Core Identity

  • 登录和注册的 View
  • AccountController
  • Model

ASP.NET Core Identity 重点类

  • UserManager:用户管理
  • SignInManager:身份认证

Identity 的具体使用

官方教程:Introduction to Identity

注册 Identity 服务并启用 Authority:

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. ...
  4. // 注册 IdentityDbContext
  5. services.AddDbContext<IdentityDbContext>(options =>
  6. options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"),
  7. b => b.MigrationsAssembly("Tutorial.Web")));
  8. // 注册 Identity 服务
  9. services.AddDefaultIdentity<IdentityUser>()
  10. .AddEntityFrameworkStores<IdentityDbContext>();
  11. // 配置 Identity
  12. services.Configure<IdentityOptions>(options =>
  13. {
  14. // Password settings.
  15. options.Password.RequireDigit = false;
  16. options.Password.RequireLowercase = false;
  17. options.Password.RequireNonAlphanumeric = false;
  18. ...
  19. });
  20. }
  21. public void Configure(
  22. IApplicationBuilder app,
  23. IHostingEnvironment env,
  24. ILogger<Startup> logger)
  25. {
  26. ...
  27. app.UseAuthentication();
  28. app.UseMvc(builder =>
  29. {
  30. builder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}");
  31. });
  32. }

注册:

  1. [HttpPost]
  2. public async Task<IActionResult> Register(RegisterViewModel registerViewModel)
  3. {
  4. if (ModelState.IsValid)
  5. {
  6. var user = new IdentityUser
  7. {
  8. UserName = registerViewModel.UserName
  9. };
  10. var result = await _userManager.CreateAsync(user, registerViewModel.PassWord);
  11. if (result.Succeeded)
  12. {
  13. return RedirectToAction("Index", "Home");
  14. }
  15. return View(registerViewModel);
  16. }
  17. return View(registerViewModel);
  18. }

登录:

  1. [HttpPost]
  2. public async Task<IActionResult> Login(LoginViewModel loginViewModel)
  3. {
  4. if (!ModelState.IsValid)
  5. {
  6. return View(loginViewModel);
  7. }
  8. var user = await _userManager.FindByNameAsync(loginViewModel.UserName);
  9. if (user != null)
  10. {
  11. var result = await _signInManager
  12. .PasswordSignInAsync(user, loginViewModel.PassWord, false, false);
  13. if (result.Succeeded)
  14. {
  15. return RedirectToAction("Index", "Home");
  16. }
  17. }
  18. ModelState.AddModelError("", "用户名/密码错误");
  19. return View(loginViewModel);
  20. }

登出:

  1. [HttpPost]
  2. public async Task<IActionResult> Logout()
  3. {
  4. await _signInManager.SignOutAsync();
  5. return RedirectToAction("Index", "Home");
  6. }

通过 Authorize 特性,限定只有登录用户才能添加学生:

  1. [Authorize]
  2. [HttpGet]
  3. public IActionResult Create()
  4. {
  5. return View();
  6. }

源码

Tutorial.zip