.net 6.0 identity实现
这里是用的现在最新的.net 6.0 ,其他版本都差不多,我这里不是在创建项目那里添加身份验证,而是基于没有身份验证后期添加进去的。
可以去官网上面看,都有相关的文档:https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/identity?view=aspnetcore-6.0&tabs=netcore-cli
1. 引用NUGET包
这里会设计到几个包
Microsoft.AspNetCore.Identity : 包含Identity自带的model类
Microsoft.Extensions.Identity.Stores : 包含了上面Identity的依赖项,新增了UserStore和RoleStore等操作项,我们看源码可以看出来
Microsoft.AspNetCore.Identity.EntityFrameworkCore :包含了上面Stores 的依赖项,还新增了IdentityDbContext的数据库EF操作
由于是包含了依赖项,只需要在Domain实体层引用 efcore这个包就行了
Microsoft.AspNetCore.Identity.EntityFrameworkCore
2. 添加DbContext
Identity自带了一些系统表,所以要生成数据库,基础设置层这里的DbContext要继承Identity提供的IdentityDbContext
3. 添加相关实体,如果不需要扩展Identity系统自带的这些表,可以忽略这一步
这里只是举了一个例子,如果需要扩展其他数据表,只需要继承相应的Idnetity实体就行了
3. 注入服务
我是基于mysql数据库的,mysql相关的依赖项这里就直接忽略了。
先配置EF DbContext生成数据库
builder.Services.AddDbContext<TestIdentityDbContext>(options => { var strdb = builder.Configuration.GetSection("dbstr").Value; options.UseMySql(strdb, ServerVersion.AutoDetect(strdb), mySqlOptionsAction => { mySqlOptionsAction.MigrationsAssembly(typeof(Program).Assembly.GetName().Name); }); });
配置 Identity
builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => { // Password settings. options.Password.RequireDigit = true; options.Password.RequireLowercase = true; options.Password.RequireNonAlphanumeric = true; options.Password.RequireUppercase = true; options.Password.RequiredLength = 6; 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; }) .AddDefaultTokenProviders() .AddEntityFrameworkStores<TestIdentityDbContext>(); //配置授权跳转 builder.Services.ConfigureApplicationCookie(cookie => { cookie.LoginPath = "/Account/FcbLogin/"; cookie.LogoutPath = "/Account/FcbLoginOut/"; cookie.AccessDeniedPath = "/Account/FcbError/"; cookie.ExpireTimeSpan = TimeSpan.FromMinutes(30); // cookie.SlidingExpiration = true; });
顺便提一下,一般授权会注入Authentication,但是idnetity 内部已经调用了AddAuthentication,所以这里不需要调用
4. 注入管道
在UseAuthorization之前注入UseAuthentication
app.UseAuthentication();
5. 添加授权
添加登入和登出,我这里只是简单测试,只是写了登入相关的东西
public ActionResult FcbLogin(string ReturnUrl) { ReturnUrl = ReturnUrl ?? Url.Content("~/"); ViewBag.ReturnUrl = ReturnUrl; return View(); } [HttpPost] public async Task<ActionResult> Login(UserLogin model) { var UserLoginInfo = await _userManager.FindByNameAsync(model.UserName); if (UserLoginInfo == null) { var user = new aspnetusers(model.UserName, model.Password); var result = await _userManager.CreateAsync(user); if (result.Succeeded) { _logger.LogInformation("注册成功"); Console.WriteLine("注册成功"); } else { _logger.LogInformation(String.Join("/r/n", result.Errors)); Console.WriteLine(String.Join("/r/n", result.Errors)); } } List<ClaimsIdentity> claimsIdentities = new List<ClaimsIdentity>(); AuthenticationProperties properties = new AuthenticationProperties() { ExpiresUtc = DateTime.UtcNow.AddMinutes(30), RedirectUri = model.ReturnUrl }; var customClaims = new List<Claim>() { new Claim("fcb", "123"), new Claim("username", "范臣斌") }; await _signInManager.SignInWithClaimsAsync(UserLoginInfo, properties, customClaims); if (string.IsNullOrEmpty(model.ReturnUrl)) { return LocalRedirect("/"); } return LocalRedirect(model.ReturnUrl); } public ActionResult FcbError() { return View(); } [HttpGet] public ActionResult FcbLoginOut() { _signInManager.SignOutAsync(); return Ok(); }
最后在需要授权的地方打上标签就行了,流程就完了
最后再测试一下访问有授权标签的 /Home/Index ,会自动跳到 /Account/FcbLogin/登录页
Perfect !!!