Asp.Net Core基于Cookie的登录、注销、验证教程
登录是用户系统必不可少的功能,Asp.Net Core默认已经集成了Cookie登录验证,使用起来也非常简单,具体看下文。
配置Startup
在startup.cs文件里,找到ConfigureServices
方法,添加
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
找到 Configure
方法,添加
app.UseCookiePolicy();
app.UseAuthentication();
登录
登录过程一般为将用户输入的用户名密码到数据库进行比对,比对成功写入cookie,比对失败就返回错误,代码如下。
public async Task<IActionResult> Login(string username, string password)
{
var success = db.valid(username,password);//数据库验证
if(!success)
{
return Content("登录失败");
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, "Administrator"),
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
//AllowRefresh = <bool>,
//ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(100),
//IsPersistent = false,
//IssuedUtc = <DateTimeOffset>,
//RedirectUri = <string>
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
return Content("登录成功");
}
退出
使用SignOutAsync
注销当前用户,并删除Cookie
await HttpContext.SignOutAsync(
CookieAuthenticationDefaults.AuthenticationScheme);
验证
在需要授权的页面,只允许已登录用户进入,这里有两种方式。
使用
AuthorizeAttribute
特性,如果未登录会跳转至 /Account/Login?ReturnUrl=path,当然这个地址是可以配置的。[Authorize] public IActionResult Test() { //使用Authorize验证 }
使用
HttpContext.User.Identity.IsAuthenticated
判断if ( HttpContext.User.Identity.IsAuthenticated ) { return Content("已登录"); } return Content("未登录");
0条评论