本文旨在演示若是使用內置的 identity 實現 asp.net core 的身份驗證,不會進行其它擴展。本文將經過最簡單的代碼演示如何進行登陸和身份驗證操做。app
咱們建立好 asp.net core 項目之後,須要在ConfigureServices中添加Authentication的服務配置,代碼以下:asp.net
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o => { o.LoginPath = new PathString("/Account/Login"); o.AccessDeniedPath = new PathString("/Account/AccessDenied"); });
而後,在Configure中添加上以下代碼,注意,UseAuthentication要放在UseMvc前面。async
app.UseAuthentication(); app.UseMvc().UseMvcWithDefaultRoute();
在完成第一步後,咱們須要添加一個控制器,來進行登陸、退出等操做,一般把這些功能放在AccountController中。關鍵代碼以下:ide
/// <summary> /// 登陸頁面 /// </summary> /// <returns></returns> public IActionResult Login() { return View(); } /// <summary> /// 模擬登陸 /// </summary> /// <param name="userName"></param> /// <returns></returns> [HttpPost] public async Task<IActionResult> Login(string userName) { //根據登陸名獲取用戶身份,以及判斷密碼等操做 var user = new SysUserIdentity { Name = userName, IsAuthenticated = true }; if (user != null) { user.AuthenticationType = CookieAuthenticationDefaults.AuthenticationScheme; var identity = new ClaimsIdentity(user); identity.AddClaim(new Claim(ClaimTypes.Name, user.Name)); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); return Redirect("/Account"); } ViewBag.Errormessage = "登陸失敗,用戶名密碼不正確"; return View(); } /// <summary> /// 退出登陸 /// </summary> /// <returns></returns> public async Task<IActionResult> Logout() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Redirect("/Account"); }
每個Action的做用以下:.net
當用戶經過上面的代碼登陸之後,在用戶訪問其它頁面時,咱們須要獲取到用戶的身份,爲了演示如何獲取到身份信息,咱們想AccountController中添加一個Index頁面,代碼以下:code
/// <summary> /// 獲取登陸人信息 /// </summary> /// <returns></returns> [Authorize] public async Task<IActionResult> Index() { var auth = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); if (auth.Succeeded) { string userName = auth.Principal.Identity.Name; //從新獲取用戶身份 var user = new SysUserIdentity() { Name = userName, IsAuthenticated = true }; return View(user); } return Redirect("~/Account/Login"); }