asp.net core 身份驗證
本文旨在演示如果使用內置的 identity 實現 asp.net core 的身份驗證,不會進行其它擴展。本文將通過最簡單的代碼演示如何進行登錄和身份驗證操作。
使用Authentication
我們創建好 asp.net core 項目以后,需要在ConfigureServices中添加Authentication的服務配置,代碼如下:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
{
o.LoginPath = new PathString("/Account/Login");
o.AccessDeniedPath = new PathString("/Account/AccessDenied");
});
然后,在Configure中添加上如下代碼,注意,UseAuthentication要放在UseMvc前面。
app.UseAuthentication();
app.UseMvc().UseMvcWithDefaultRoute();
添加Account控制器
在完成第一步后,我們需要添加一個控制器,來進行登錄、退出等操作,通常把這些功能放在AccountController中。關鍵代碼如下:
/// <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的作用如下:
- Login - Get:用來響應Get請求,提供用戶輸入用戶名、密碼的頁面。
- Login - Post:用來響應Post請求,對用戶輸入的用戶名和密碼進行驗證,驗證通過后分發票據
- Logout - Get:用來響應Get請求,退出登錄。
獲取用戶身份
當用戶通過上面的代碼登錄以后,在用戶訪問其它頁面時,我們需要獲取到用戶的身份,為了演示如何獲取到身份信息,我們想AccountController中添加一個Index頁面,代碼如下:
/// <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");
}