ASP.net Core 登陸驗證CookieAuthenticationDefaults/ClaimsPrincipal
阿新 • • 發佈:2018-12-16
一、在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}"); }); }
二、登陸
[OperationLogFilter("Select")] public IActionResult Index(string returnUrl = null) //登陸成功回退頁面 { TempData["returnUrl"] = returnUrl; return View(); } [HttpPost] [OperationLogFilter("Login",Tag ="登陸")] public async Task<IActionResult> 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)); return RedirectToAction(nameof(HomeController.HomeIndex), "Home"); }
三、登出
public async Task<IActionResult> 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(); }