Asp.net core mvc 如何使用 cookie 登陆认证
实现登陆功能,主要代码分布在两个物理文件上,当然你也可以自己独特的设计,我这里就讲最常见的情况。一个文件是Startup.cs,一个是你的登陆控制器文件。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)


1. Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//...
app.UseStaticFiles();
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme,
LoginPath = new PathString("/"),
AccessDeniedPath = new PathString("/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
//。。。
}
如下图,是生产环境的代码

加上如上标注斜体的代码所示,“/”斜杠意思是重定向到的路径,我这里重定向到首页。
2. 控制器
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Email, account.UserId, ClaimValueTypes.String));
claims.Add(new Claim(ClaimTypes.Name, account.UserName, ClaimValueTypes.String));
ClaimsIdentity identity = new ClaimsIdentity(claims, account.Id.ToString());
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(linfo.Expires),
IsPersistent = false,
AllowRefresh = false
});
登陆代码也很简单,照官方文档做就是,而且也容易理解。

里面包含了我的登陆的业务代码,不影响阅读,而现实的项目中也一定会用到的。
Posted by 何敏 on 2017/6/3 14:18:33