這里是用的現在最新的.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 !!!