Hi @winanjaya ,
You can add a RememberMe property to your model, like:
public class User
{
...
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
Then in your login page add "remember me" option, like:
<div class="form-group">
<div class="checkbox">
<label>
<input asp-for="RememberMe" /> @Html.DisplayNameFor(model => model.RememberMe)
</label>
</div>
</div>
At last , in your Login post HttpContext.SignInAsync method add :
new AuthenticationProperties
{
IsPersistent = user.RememberMe
});
My test code like:
[HttpPost]
public async Task<IActionResult> Login(User model)
{
if (ModelState.IsValid)
{
User user = await _context.Users
.FirstOrDefaultAsync(u => u.Email == model.Email && u.Password == model.Password);
if (user != null)
{
user.RememberMe = model.RememberMe;
await Authenticate(user);
return RedirectToAction("Index", "HomePage");
}
else
{
ModelState.AddModelError("", "error");
}
}
return View(model);
}
private async Task Authenticate(User user)
{
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email),
new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role)
};
ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id),
new AuthenticationProperties
{
IsPersistent = user.RememberMe
});
}
The HomePage like:
@if (User.Identity.IsAuthenticated )
{
<a style="color: green">Hello @User.Identity?.Name!</a>
}
Result:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Qing Guo