網站,首先須要安全,實現安全就必須使用登陸驗證,.net core 基於Claim登陸驗證就很簡單使用。安全
Claim是什麼,能夠理解爲你的身份證的中的名字,性別等等的每一條信息,而後Claim組成一個ClaimIdentity 就是組成一個身份證。服務器
那麼咱們.net core 是如何基於Claim實現登陸驗證呢cookie
首先咱們須要在startup中配置:app
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(); //添加中間件 }
而後咱們須要在咱們的登陸用戶名和密碼的表中添加這個字段async
/// <summary> /// 屬性標識此身份驗證模塊實現的身份驗證類型 /// </summary> public string AuthenticationType { get; internal set; }
而後咱們在登陸的控制器寫登陸方法ide
/// <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] 特性以後,每次請求該控制器的方法都會驗證。ui
基於Claim的登陸驗證就是這些,若是有錯誤請指正。