ASP.net Core Cookie登陆验证

Cookie使用的加密方式是ASP.NET Core的Data Protection系统。如果您在多台机器上进行托管、负载平衡或使用Web集群,则需要配置Data Protection才能使用相同的密钥和应用程序标识符。

一、在StartUp中注册服务

public IServiceProvider ConfigureServices(IServiceCollection services)
{
       services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
               .AddCookie(options => options.LoginPath = new             
               PathString("/Login/Index")); //登陆页面
       services.AddMvc();
       this.ApplicationContainer = AutoFacIoc.Injection(services);
       return new AutofacServiceProvider(this.ApplicationContainer);
}

		// 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();
	   }
       //使用静态文件
       app.UseStaticFiles();
       //启用登陆验证
       app.UseAuthentication();
       //路由
       app.UseMvc(routes =>
       {
          routes.MapRoute(
                 name: "default",
                 template: "{controller=Home}/{action=HomeIndex}/{id=0}");
       });

}

二、登陆

        
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;

        [OperationLogFilter("Select")]
        public IActionResult Index(string returnUrl = null) //登陆成功回退页面
        {
            TempData["returnUrl"] = returnUrl;
            return View();
        }

        [HttpPost]
        [OperationLogFilter("Login",Tag ="登陆")]
        public async Task Login(ApplicationUser user, string returnUrl = null)
        {
           //做参数验证!!! 和用户信息认证

            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            //可以放用户唯一标识。 然后再BaseController中使用User.Identity.Name获取, 再查询数据库/缓存获取用户信息
            identity.AddClaim(new Claim(ClaimTypes.Name, lookupUser.UserName)); //取值 User.Identity.Name
            identity.AddClaim(new Claim(ClaimTypes.UserData, "456465465456")); // User.Claims.Select(t => new { t.Type, t.Value }).ToList();
            identity.AddClaim(new Claim(ClaimTypes.Surname, "王小二"));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "123"));

           
            await 
             HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties
            {
                //IsPersistent = false, //true:保持登陆不过期 false:关闭浏览器就过期
                ExpiresUtc = DateTime.UtcNow.AddSeconds(10) // 10秒钟不操作就过期
            });

            return RedirectToAction(nameof(HomeController.HomeIndex), "Home");
        }

三、登出

public async Task Logout()
{
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("HomeIndex", "Home");
}

四、获取登陆信息

        [AuthFilter]
        public IActionResult HomeIndex()
        {
            string a  = User.Identity.Name; //一般用于存储用户唯一标识
            string type = User.Identity.AuthenticationType; //验证方式
            var temp = User.Claims.Select(t => new { t.Type, t.Value }).ToList();
            var tt= temp[0].Type;
            return  View();
        }

 

你可能感兴趣的:(.net,Core)