網站,首先需要安全,實現安全就必須使用登錄驗證,.net core 基於Claim登錄驗證就很簡單使用。
Claim是什么,可以理解為你的身份證的中的名字,性別等等的每一條信息,然后Claim組成一個ClaimIdentity 就是組成一個身份證。
那么我們.net core 是如何基於Claim實現登錄驗證呢
首先我們需要在startup中配置:
public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o => { o.LoginPath = new PathString("/Login"); // 登錄頁面的url o.AccessDeniedPath = new PathString("/Login");//沒有授權跳轉的頁面 o.ExpireTimeSpan = TimeSpan.FromHours(0.5); // cookies的過期時間 });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseAuthentication(); //添加中間件 }
然后我們需要在我們的登錄用戶名和密碼的表中添加這個字段
/// <summary> /// 屬性標識此身份驗證模塊實現的身份驗證類型 /// </summary> public string AuthenticationType { get; internal set; }
然后我們在登錄的控制器寫登錄方法
/// <summary> /// 登錄 /// </summary> /// <param name="name">用戶名</param> /// <param name="password">密碼</param> /// <returns></returns> [HttpGet("login/{name}/{password}")] public async Task<IActionResult> Login(string name, string password) { var user = userLogicHandler.GetUsers(name, password); if (user !=null) { user.AuthenticationType = CookieAuthenticationDefaults.AuthenticationScheme; var identity = new ClaimsIdentity(user.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserId)); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); return Ok(200); } else { return Ok(500); } }
登錄的時候上傳密碼和名稱到服務器中,如果匹配,那么服務器會將ClaimsIdentity保存到客戶端中的cookies中,然后每次請求需要驗證的控制器的時候就會驗證是否有ClaimIdentity。
[Hidden] [Route("Home")] [Authorize] public class HomeController : Controller { /// <summary> /// 主界面 /// </summary> /// <returns></returns> [HttpGet] public IActionResult Home() { return View(); }
如上,加上[Authorize] 特性之后,每次請求該控制器的方法都會驗證。
基於Claim的登錄驗證就是這些,如果有錯誤請指正。