Cookie-base 认证实现(学习笔记)
第一步 新建一个ASP.NET core 默认项目
新建 AdminController
public class AdminController : Controller { [Authorize] //打上authorize 验证标签 public IActionResult Index() { return View(); } }
添加 accountController 模拟用户登录 登出
public class AccountController : Controller { public IActionResult MakeLogin() { //claims 对被验证主体特征的一种表述,比如:登录用户名是...,email是...,用户Id是...,其中的“登录用户名”,“email”,“用户Id”就是ClaimType。 var claims=new List<Claim>(){ new Claim(ClaimTypes.Name,"zengpeng"),new Claim(ClaimTypes.Role,"admin") }; //claims,CookieAuthenticationDefaults.AuthenticationScheme 验证协议 var claimidentity=new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(claimidentity)); return Ok(); } public IActionResult LogOut() { //claims 对被验证主体特征的一种表述,比如:登录用户名是...,email是...,用户Id是...,其中的“登录用户名”,“email”,“用户Id”就是ClaimType。 HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Ok(); } }
在start up类中 添加相关中间件
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //添加Authentication 验证 传入Schema 最后添加cookie addCookie 中的option 为可选 参数 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie( opthions=>{opthions.LoginPath="/Account/MakeLogin"; //当用户没有登录的时候 跳转到当前制定的页面 //opthions.AccessDeniedPath="/Account/MakeLogin"; 当用户没有权限访问时候 跳转的页面 } ); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); //添加验证的middware app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
2016-02-22 windows服务