ASP.NET Core分布式项目实战(集成ASP.NETCore Identity)--学习笔记
任務24:集成ASP.NETCore Identity
之前在 Index 頁面寫了一個 strong 標簽,需要加個判斷再顯示,不然為空沒有錯誤的時候也會顯示
@if (!ViewContext.ModelState.IsValid) {<strong>Error""</strong><div asp-validation-summary="All" class="danger"></div> }因為 asp-validation-summary 是 asp.net view 視圖會自動控制,而 strong 不會,所以要顯示標題需要添加一個判斷,那么這里我們直接移除掉,當有錯誤信息的時候直接顯示即可,這里作為上一節的補充
<div asp-validation-summary="All" class="danger"></div>這一節主要把 Identity 加入進來
一開始我們把 startup 中的 Identity 注釋掉了,只需要開啟即可
添加包 IdentityServer4,IdentityServer4.AspNetIdentity,添加之后就可以把 AddTestUsers 移除掉,它就不會再用測試里面的 user,
Startup.cs
public void ConfigureServices(IServiceCollection services) {services.AddDbContext<ApplicationDbContext>(options =>{options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));});services.AddIdentity<ApplicationUser, ApplicationUserRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();services.AddIdentityServer().AddDeveloperSigningCredential().AddInMemoryClients(Config.GetClients()).AddInMemoryApiResources(Config.GetApiResource()).AddInMemoryIdentityResources(Config.GetIdentityResources()).AddAspNetIdentity<ApplicationUser>();//services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)// .AddCookie(options => {// options.LoginPath = "/Account/Login";// });//services.Configure<IdentityOptions>(options =>//{// options.Password.RequireLowercase = true;// options.Password.RequireNonAlphanumeric = true;// options.Password.RequireUppercase = true;// options.Password.RequiredLength = 12;//});services.AddScoped<ConsentService>();services.AddMvc(); }接下來要到 AccountController 中切換回原先的登錄邏輯
AccountController
private UserManager<ApplicationUser> _userManager; private SignInManager<ApplicationUser> _signInManager; private IIdentityServerInteractionService _interaction;//private readonly TestUserStore _users;//public AccountController(TestUserStore users) //{ // _users = users; //}public AccountController(UserManager<ApplicationUser> userManager,SignInManager<ApplicationUser> signInManager,IIdentityServerInteractionService interaction) {_userManager = userManager;_signInManager = signInManager;_interaction = interaction; }接下來改造 AccountController 的 Register 方法,首先把 RegisterViewModel 的 UserName 改回為 Email
RegisterViewModel
public string Email { get; set; } //public string UserName { get; set; }AccountController
[HttpPost] public async Task<IActionResult> Register(RegisterViewModel registerViewModel, string returnUrl = null) {if (ModelState.IsValid){ViewData["ReturnUrl"] = returnUrl;var identityUser = new ApplicationUser{Email = registerViewModel.Email,UserName = registerViewModel.Email,NormalizedUserName = registerViewModel.Email,};var identityResult = await _userManager.CreateAsync(identityUser, registerViewModel.Password);if (identityResult.Succeeded){await _signInManager.SignInAsync(identityUser, new AuthenticationProperties { IsPersistent = true });return RedirectToLoacl(returnUrl);}else{AddErrors(identityResult);}}return View(); }接著改造 AccountController 的 Login 方法,首先把 LoginViewModel 的 UserName 也改回為 Email,并加上一個 RememberMe 字段
LoginViewModel
public string Email { get; set; } //public string UserName { get; set; } public bool RememberMe { get; set; }調用 UserManager 的查找和登錄的邏輯
AccountController
[HttpPost] public async Task<IActionResult> Login(LoginViewModel loginViewModel,string returnUrl) {if (ModelState.IsValid){ViewData["ReturnUrl"] = returnUrl;var user = await _userManager.FindByEmailAsync(loginViewModel.Email);if (user == null){ModelState.AddModelError(nameof(loginViewModel.Email), "Email not exists");}else{if (await _userManager.CheckPasswordAsync(user, loginViewModel.Password)){AuthenticationProperties props = null;if (loginViewModel.RememberMe){props = new AuthenticationProperties{IsPersistent = true,ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30)),};}await _signInManager.SignInAsync(user, props);if (_interaction.IsValidReturnUrl(returnUrl)){return Redirect(returnUrl);}return Redirect("~/");}ModelState.AddModelError(nameof(loginViewModel.Password), "Wrong Password");}}return View(loginViewModel); }還原 Logout 方法
Logout
public async Task<IActionResult> Logout() {await _signInManager.SignOutAsync();//await HttpContext.SignOutAsync();return RedirectToAction("Index", "Home"); }檢查一下 view,將 Login.cshtml 里面的 UserName 修改為 Email,model 改為 LoginViewModel
Login.cshtml
@model LoginViewModel;恢復 Program 中 EF 的初始化
Program
public static void Main(string[] args) {BuildWebHost(args).MigrateDbContext<ApplicationDbContext>((context, services) =>{new ApplicationDbContextSeed().SeedAsync(context, services).Wait();}).Run(); }啟動程序之后會根據 appsettings.json 中的配置創建數據庫
appsettings.json
"ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-IdentitySample-CE9DD12E-9C3B-4072-8E38-6F33420849CB;Trusted_Connection=True;MultipleActiveResultSets=true" }編譯啟動程序,可以看到用戶表有一條數據
這條數據來自 ApplicationDbContextSeed
public class ApplicationDbContextSeed {private UserManager<ApplicationUser> _userManager;public async Task SeedAsync(ApplicationDbContext context, IServiceProvider services){if (!context.Users.Any()){_userManager = services.GetRequiredService<UserManager<ApplicationUser>>();var defaultUser = new ApplicationUser {UserName="Administrator",Email ="jessetalk@163.com",NormalizedUserName ="admin"};var result = await _userManager.CreateAsync(defaultUser, "Password$123");if (!result.Succeeded){throw new Exception("初始默認用戶失敗");}}} }瀏覽器訪問
http://localhost:5000/使用郵箱登錄
退出登錄之后啟動客戶端,瀏覽器訪問 5001 之后會跳轉到 5000
http://localhost:5001/輸入郵箱和密碼之后會來到 consent 頁面
點擊同意之后跳轉到 MvcClient
點擊 About 看到用戶名是 Administrator,就是數據庫里面的用戶
這就是我們把程序里面的 TestUserStore 替換為 Identity
課程鏈接
http://video.jessetalk.cn/course/explore
相關文章
ASP.NET Core分布式項目實戰(Consent 代碼重構)--學習筆記
ASP.NET Core分布式項目實戰(Consent 確認邏輯實現)--學習筆記
ASP.NET Core分布式項目實戰(運行Consent Page)--學習筆記
ASP.NET Core分布式項目實戰(Consent Controller Get請求邏輯實現)--學習筆記
ASP.NET Core分布式項目實戰(Consent視圖制作)--學習筆記
ASP.NET Core分布式項目實戰(Identity Server 4回顧,Consent 實現思路介紹)--學習筆記
ASP.NET Core分布式項目實戰(oauth2 + oidc 實現 client部分)--學習筆記
ASP.NET Core分布式項目實戰(oauth2 + oidc 實現 server部分)--學習筆記
ASP.NET Core分布式項目實戰(oauth2與open id connect 對比)--學習筆記
ASP.NET Core分布式項目實戰(詳解oauth2授權碼流程)--學習筆記
ASP.NET Core分布式項目實戰(oauth密碼模式identity server4實現)--學習筆記
ASP.NET Core分布式項目實戰(第三方ClientCredential模式調用)--學習筆記
ASP.NET Core分布式項目實戰(客戶端集成IdentityServer)--學習筆記
ASP.NET Core分布式項目實戰(業務介紹,架構設計,oAuth2,IdentityServer4)--學習筆記
ASP.NET Core分布式項目實戰(課程介紹,MVP,瀑布與敏捷)--學習筆記
ASP.NET Core快速入門 -- 學習筆記匯總
總結
以上是生活随笔為你收集整理的ASP.NET Core分布式项目实战(集成ASP.NETCore Identity)--学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微前端与项目实施方案研究
- 下一篇: Dotnet core基于ML.net的