先随便贴点代码

1、WebApi_Net7使用Cookie

// 开启Cookie
using Microsoft.AspNetCore.CookiePolicy;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using System;

namespace fly_chat1_net7
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // try前也可能报错,但是错误是可控的。实际项目中使用时可以再加个try,只记录日志到文件中。
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())  // 设置“configuration”的查找目录为程序目录
                .AddJsonFile("appsettings.json")  // 设置“configuration”的读取文件
                .Build();  // 获取配置

                var builder = WebApplication.CreateBuilder(args);

                #region 容器Services
                builder.Services.AddControllers();            // 添加Controller
                builder.Services.AddHttpContextAccessor();    // 操作Http上下文;比如:AOP里面可以获取IOC对象
                builder.Services.AddEndpointsApiExplorer();   // ASP.NET Core自身提供;Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

                #region Cookie与Session
                builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)  // 起用Cookie认证
                builder.Services.AddCookiePolicy(options =>
                {
                    options.MinimumSameSitePolicy = SameSiteMode.Lax;  // 限制只使用同站Cookie;Chrome 51 开始,浏览器的 Cookie 新增加了一个SameSite属性,用来防止 CSRF 攻击和用户追踪。SameSiteMode.Lax 允许 OAuth2身份验证,如Get请求;SameSiteMode.Strict 严格执行同一站点策略。
                    options.Secure = CookieSecurePolicy.None;          // 标识Cookie是否必须是https。该属性在SameSite=None的场景下生效;CookieSecurePolicy.None为允许Https/Http,CookieSecurePolicy.Always为只允许Https;CookieSecurePolicy.SameAsRequest为登录页的URI是Https时则只允许Https,URI是Http时则允许Http/Https。
                    options.HttpOnly = HttpOnlyPolicy.None;            // 是否只在Http请求中启用Cookie;默认为开启
                    options.CheckConsentNeeded = _ => true;            // 检查用户是否位于欧盟(EU)或欧洲经济区(EEA);是则弹出一个页面让用户同意Cookie跟踪策略。默认是“false”
                    options.ConsentCookieValue = "true";               // 是否弹出一个页面让用户同意Cookie跟踪策略;默认为“是”。与CheckConsentNeeded类似。
                    options.ConsentCookie = new CookieBuilder()        // options.CheckConsentNeeded或options.ConsentCookieValue弹出页面的内容
                    {
                        Name = configuration["AppName"],     // Cookie名字
                        Expiration = TimeSpan.FromHours(6),  // Cookie过期时间-6小时
                        MaxAge = TimeSpan.FromHours(6),      // Cookie最大生命周期-6小时;Expiration与MaxAge如果同时使用,MaxAge会生效;推荐使用MaxAge。
                        IsEssential = false,                 // 是否可绕过"检查同意政策",默认为false不绕过
                    };
                    //options.OnAppendCookie = CheckSameCookie => { };  // cookie添加事件-记录Cookie变化或者检查是否有相同的Cookie
                    //options.OnDeleteCookie = AddCookieLog => { };     // cookie删除事件-记录Cookie变化
                });
                #endregion Cookie与Session
                #endregion 容器Services

                var app = builder.Build();
                app.UseHttpLogging();

                app.UseCookiePolicy();  // 启用Cookie
                app.UseAuthorization();
                app.MapControllers();
                app.Run();
            }
            
        }
    }
}

补充:options配置

  ①Name 默认为 SessionDefaults.CookieName (.AspNetCore.Session)。

  ②Path 默认为 SessionDefaults.CookiePath (/)。 

  ③SameSite 默认为 SameSiteMode.Lax (1)。 

  ④HttpOnly 默认为 true。 IsEssential 默认为 false

2、用户登录(Cookie+ClaimsPrincipal序列化记录并验证用户身份信息)

public async Task<string> SignIn_CoookieAsync(string email,string password)
{

        // Use Input.Email and Input.Password to authenticate the user
        // with your custom authentication logic.
        //
        // For demonstration purposes, the sample validates the user
        // on the email address maria.rodriguez@contoso.com with 
        // any password that passes model validation.

        var user = await AuthenticateUser(email, password);  // Authenticatede 认证方法

        if (user == null)
        {
            return "登录失败!用户名或密码错误"; 
        }

        var claims = new List<Claim>  // 维护用户信息
        {
            new Claim(ClaimTypes.Name, user.Email),
            new Claim("FullName", user.FullName),
            new Claim(ClaimTypes.Role, "Administrator"),
        };

        var claimsIdentity = new ClaimsIdentity(  // claims添加到claimsIdentity
            claims, CookieAuthenticationDefaults.AuthenticationScheme);

        var authProperties = new AuthenticationProperties
        {
            //AllowRefresh = <bool>,
            // Refreshing the authentication session should be allowed.

            //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
            // The time at which the authentication ticket expires. A 
            // value set here overrides the ExpireTimeSpan option of 
            // CookieAuthenticationOptions set with AddCookie.

            //IsPersistent = true,
            // Whether the authentication session is persisted across 
            // multiple requests. When used with cookies, controls
            // whether the cookie's lifetime is absolute (matching the
            // lifetime of the authentication ticket) or session-based.

            //IssuedUtc = <DateTimeOffset>,
            // The time at which the authentication ticket was issued.

            //RedirectUri = <string>
            // The full path or absolute URI to be used as an http 
            // redirect response value.
        };

        await HttpContext.SignInAsync(  // 执行登录操作;SignInAsync 将创建加密的 cookie 并将其添加到当前响应中
            CookieAuthenticationDefaults.AuthenticationScheme, 
            new ClaimsPrincipal(claimsIdentity), 
            authProperties);

        _logger.LogInformation("User {Email} logged in at {Time}.",   // 记录调用日志
            user.Email, DateTime.UtcNow);

        return "登录成功!";
}

3、用户注销

public async Task SignOut_CookieAsync()
{
    // Clear the existing external cookie
    await HttpContext.SignOutAsync(
        CookieAuthenticationDefaults.AuthenticationScheme);
}

作者:꧁执笔小白꧂