ASP.net Core 登陆验证CookieAuthenticationDefaults/ClaimsPrincipal
程序员文章站
2023-12-28 20:36:22
...
一、在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();
}
推荐阅读
-
ASP.net Core 登陆验证CookieAuthenticationDefaults/ClaimsPrincipal
-
asp.net core系列之模型绑定和验证方法
-
Asp.Net Core中基于Session的身份验证的实现
-
基于ASP.NET Core数据保护生成验证token示例
-
asp.net core系列之模型绑定和验证方法
-
详解ASP.NET与ASP.NET Core用户验证Cookie并存解决方案
-
Asp.Net Core中基于Session的身份验证的实现
-
ASP.NET Core & 双因素验证2FA 实战经验分享
-
详解ASP.NET Core和ASP.NET Framework共享身份验证
-
使用ASP.NET Core 3.x 构建 RESTful API - 5.1 输入验证