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?}");
            });
        }
    }
}
原文地址:https://www.cnblogs.com/zengpeng/p/8458149.html