Asp.Net Core Identity
1.特点:
1)身份认证和授权系统
2)成员管理
3)默认使用MSSQL
4)支持外部的Provider
2.Asp.Net Core Identity重点类
1)SignInManager<IdentityUser>
2)UserManager<IdentityUser>
3.使用
1)结构:
①控制器:AccountController.cs
②模型:LoginViewModel.cs、RegisterViewModel.cs
③页面:Login.cshtml、Register.cshtml
④生成配置:Startup.cs
2)代码:
①AccountController.cs
使用: SignInManager<IdentityUser>和UserManager<IdentityUser>
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CoreTest.Web.ViewModel; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; namespace CoreTest.Web.Controllers { 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; } [HttpGet] public IActionResult Login() { return View(); } /// <summary> /// 登录 /// </summary> /// <param name="login"></param> /// <returns></returns> [HttpPost] public async Task<IActionResult> Login(LoginViewModel login) { if (!ModelState.IsValid) { return View(login); } //通过用户名获取用户信息 var user = await _userManager.FindByNameAsync(login.UserName); //验证密码 if (user != null) { var result = await _signInManager .PasswordSignInAsync(user,login.Password,false,false); if (result.Succeeded) { return RedirectToAction("Index","Home"); } } ModelState.AddModelError("","用户名/密码不正确!"); return View(login); } [HttpGet] public IActionResult Register() { return View(); } /// <summary> /// 注册 /// </summary> /// <param name="register"></param> /// <returns></returns> [HttpPost] public async Task<IActionResult> Register(RegisterViewModel register) { if (ModelState.IsValid) { //创建用户注册 var user = new IdentityUser { UserName = register.UserName }; var result = await _userManager.CreateAsync(user,register.Password); if (result.Succeeded) { return RedirectToAction("Index", "Home"); } } return View(register); } /// <summary> /// 登出 /// </summary> /// <returns></returns> [HttpPost] public async Task<IActionResult> Logout() { await _signInManager.SignOutAsync(); return RedirectToAction("Index", "Home"); } } }
②模型:
LoginViewModel.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace CoreTest.Web.ViewModel { /// <summary> /// 登录 /// </summary> public class LoginViewModel { /// <summary> /// 用户名 /// </summary> [Required] [Display(Name = "用户名")] public string UserName {get;set;} /// <summary> /// 密码 /// </summary> [Required] [DataType(DataType.Password)] [Display(Name = "密码")] public string Password { get; set; } } }
RegisterViewModel.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace CoreTest.Web.ViewModel { /// <summary> /// 注册 /// </summary> public class RegisterViewModel { /// <summary> /// 用户名 /// </summary> [Required] [Display(Name = "用户名")] public string UserName { get; set; } /// <summary> /// 密码 /// </summary> [Required] [Display(Name = "密码")] public string Password { get; set; } } }
③页面:
Login.cshtml
@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> <input type="submit" value="提交" /> <div asp-validation-summary="All"></div> </form>
Register.cshtml
@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> <input type="submit" value="提交" /> <div asp-validation-summary="All"></div> </form>
④生成配置:
修改Startup.cs(授权配置:红色部分)
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using CoreTest.Web.Data; using CoreTest.Web.Model; using CoreTest.Web.Service; using CoreTest.Web.Setting; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; namespace CoreTest.Web { public class Startup { private readonly IConfiguration _configuration; public Startup(IConfiguration configuration) { _configuration = configuration; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //只有一个实例 services.AddSingleton<IWelcome,IWelcomeService>(); //每次一个新的Http请求,产生一个新的实例 services.AddScoped<IRepository<Student>,InMemoryRepository>(); //使用数据连接 services.AddDbContext<CoreTestDbContext>(options => { //获取数据连接 options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")); }); //授权注册 services.AddDefaultIdentity<IdentityUser>() .AddEntityFrameworkStores<IdentityDbContext>(); //授权表生成 services.AddDbContext<IdentityDbContext>(options => options.UseSqlServer( _configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("CoreTest.Web")//作用的程序集 )); //授权密码设定 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 = true; // User settings. options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; options.User.RequireUniqueEmail = false; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env,IConfiguration configuration, IWelcome welcomeService) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(); } app.UseMvc(); app.UseStaticFiles(); //app.UseDefaultFiles(); app.UseStaticFiles(new StaticFileOptions { RequestPath= "/node_modules", FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules")) }); //app.UseMvcWithDefaultRoute(); //app.UseWelcomePage(); app.UseAuthentication(); app.UseMvc(route => { route.MapRoute("Default", "{Controller=Home}/{Action=Index}/{id?}"); }); //app.Run(async (context) => //{ // var hell = configuration["DZW"]; // var hell2 = welcomeService.GetMessage(); // await context.Response.WriteAsync(hell2); //}); } } }
3)数据库生成
①打开程序包管理器控制台
②执行 add-migration CoreTest2 生成数据库执行文件语句(注:这个时候会报错,因为项目配置中有两个不同烦人数据库链接--Identity和appsettings.json的数据库链接)
提示:
这个时候,我们将指明具体的声称对象,执行:add-migration CoreTest3 -Context IdentityDbContext
③生成数据库
执行:Update-database -Context IdentityDbContext
4)Layout判断是否登录显示用户名
使用
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@using Microsoft.AspNetCore.Identity <!DOCTYPE html> @inject SignInManager<IdentityUser> SignInManager <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> </head> <body> @*判断是否登录*@ @if (SignInManager.IsSignedIn(User)) { <form asp-controller="Account" asp-action="Logout" method="post" id="logoutForm"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a href="javascript:document.getElementById('logoutForm').submit()">登出</a> </li> </ul> </form> } else { <a asp-action="Register" asp-controller="Account">注册</a> <a asp-action="Login" asp-controller="Account">登录</a> } <h1>11111</h1> <div> @RenderBody() </div> <hr /> @RenderSection("bottom", required: false) <vc:welcome-student-components></vc:welcome-student-components> <script src="~/node_modules/jquery/dist/jquery.min.js"></script> <script src="~/node_modules/jquery-validation/dist/jquery.validate.min.js"></script> <script src="~/node_modules/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"></script> </body> </html>
5)使用展示
①登录前:
②登录后:
③授权验证限制:在对应调用的控制器或页面前面加上[Authorize]
感谢:杨老师
参阅:https://www.bilibili.com/video/av38392956/?p=14