Net Core Authentication Cookie
Configuration
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(p => {
p.LoginPath = "/auth/login";
p.LogoutPath = "/auth/logout";
p.AccessDeniedPath = "/auth/denined";
p.Cookie.Name = "cebnetvn";
p.ExpireTimeSpan = TimeSpan.FromDays(30);
});
Create Class LoginModel
public class LoginModel{
public string U { get; set; } = null!;
public string P { get; set; } = null!;
public bool R { get; set; }
}
Create Authentication Controller
public class AuthController : Controller{
[Authorize]
public IActionResult Index() => View();
public IActionResult Login() => View();
[HttpPost]
public async Task<IActionResult> Login(LoginModel obj){
if(obj.U.Equals("thanh") && obj.P.Equals("123")){
List<Claim> claims = new List<Claim>{
new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Name, obj.U)
};
ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(new ClaimsPrincipal(identity), new AuthenticationProperties{ IsPersistent = obj.R});
return Redirect("/auth");
}
return View(obj);
}
}