ASP.NETCore-中间件Middleware(四)_认证+授权中间件-Cookie
先随便贴点代码
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);
}
本文来自博客园,作者:꧁执笔小白꧂,转载请注明原文链接:https://www.cnblogs.com/qq2806933146xiaobai/articles/17464882.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
2021-06-07 Untiy 跳转场景