關於asp.net core 的文章,博客園已經有很多大牛寫過了。
這里我只是記錄下自己在學習中的點滴和一些不懂的地方
Cookie一般是用戶網站授權,當用戶訪問需要授權(authorization)的頁面,程序會判斷是否已經授權,並認證

添加認證代碼:
引入命名空間:Microsoft.AspNetCore.Authentication.Cookies;
添加服務
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(); }
注冊中間件,添加到管道
app.UseAuthentication();
注意:一定要在app.UseMvc之前添加
我們通過源碼可以看到cookie的一些默認配置
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Authentication.Cookies { /// <summary> /// Default values related to cookie-based authentication handler /// </summary> public static class CookieAuthenticationDefaults { /// <summary> /// The default value used for CookieAuthenticationOptions.AuthenticationScheme /// </summary> public const string AuthenticationScheme = "Cookies"; /// <summary> /// The prefix used to provide a default CookieAuthenticationOptions.CookieName /// </summary> public static readonly string CookiePrefix = ".AspNetCore."; /// <summary> /// The default value used by CookieAuthenticationMiddleware for the /// CookieAuthenticationOptions.LoginPath /// </summary> public static readonly PathString LoginPath = new PathString("/Account/Login"); /// <summary> /// The default value used by CookieAuthenticationMiddleware for the /// CookieAuthenticationOptions.LogoutPath /// </summary> public static readonly PathString LogoutPath = new PathString("/Account/Logout"); /// <summary> /// The default value used by CookieAuthenticationMiddleware for the /// CookieAuthenticationOptions.AccessDeniedPath /// </summary> public static readonly PathString AccessDeniedPath = new PathString("/Account/AccessDenied"); /// <summary> /// The default value of the CookieAuthenticationOptions.ReturnUrlParameter /// </summary> public static readonly string ReturnUrlParameter = "ReturnUrl"; } }
我們可以自己修改:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(option => { option.LoginPath = "/Login"; //沒有授權,跳轉的url option.LogoutPath = "/Login"; //退出,的url });
因為cookie在有效期內都是有效的,如果用戶資料修改了,客戶端的Cookie是不知道的
網上有人提出了解決方案,如果用戶修改了資料,在數據庫用一個字段記錄,cookie有個事件,在每次請求都會訪問
option.Events.OnValidatePrincipal = ValidatePrincipal
想添加多個可以這樣寫:
option.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = ValidatePrincipal,
//OnRedirectToLogin =
};
public async Task ValidatePrincipal(CookieValidatePrincipalContext context) { var _Context = context.HttpContext.RequestServices.GetRequiredService<EFContext>(); var s = context.HttpContext.RequestServices.GetService<EFContext>(); var principal = context.Principal; var u = principal.Claims.Select(c => c.Type == "isEdit").FirstOrDefault(); if (u) { //更新數據庫狀態 // // 1. 驗證失敗 等同於 Principal = principal; context.RejectPrincipal(); //登出 await AuthenticationHttpContextExtensions.SignOutAsync(context.HttpContext, CookieAuthenticationDefaults.AuthenticationScheme); // 2. 驗證通過,並會重新生成Cookie。 //context.ShouldRenew = true; } }
用戶登陸,網上有人這里解釋的
ClaimsIdentity(身份證),Claims(身份信息)
ClaimsPrinciple (證件所有者)
這個也很恰當
https://www.cnblogs.com/dudu/p/6367303.html
[HttpPost] public async Task<IActionResult> Login(string ReturnUrl, User model) { if (model.UserName=="cnblogs" && model.PassWord == "pwd") { /* ClaimsIdentity(身份證),Claims(身份信息) ClaimsPrinciple (證件所有者) */ //身份信息 var claims = new List<Claim> { new Claim(ClaimTypes.Name,"sky"), new Claim("Address","北京海淀"), }; //身份證 var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); //證件所有者 var claimsPrinciple = new ClaimsPrincipal(claimsIdentity); /* 如果登陸選擇了記住我,則將cookie持久化 這里默認持久化 */ var properties = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1), //ExpiresUtc = DateTime.Now.AddDays(1) }; await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrinciple, properties); return Redirect(ReturnUrl); } else return View("index"); }
博客園的大神文章,很多。就放幾個參考吧
https://www.cnblogs.com/RainingNight/p/7587194.html
https://www.cnblogs.com/tdfblog/p/7416589.html
