I started developing websites using ASP.Net Core 2.2. I'm implementing login/logout by a custom cookie authentication (not Identity).
Please see or clone the repo:
git clone https://github.com/mrmowji/aspcore-custom-cookie-authentication.git .
... or read the following code snippets.
Here is the code in Startup.cs
:
public void ConfigureServices(IServiceCollection services) {
...
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
options.LoginPath = new PathString("/login");
options.ExpireTimeSpan = TimeSpan.FromDays(30);
options.Cookie.Expiration = TimeSpan.FromDays(30);
options.SlidingExpiration = true;
});
...
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
...
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
...
Here is the code of Login
action:
public async Task<IActionResult> Login(LoginViewModel userToLogin) {
var username = "username"; // just to test
var password = "password"; // just to test
if (userToLogin.UserName == username && userToLogin.Password == password) {
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, "admin"),
new Claim(ClaimTypes.Role, "Administrator"),
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties {
AllowRefresh = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddDays(10),
IsPersistent = true,
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
...
Cookies are set as expected. I have a .AspNetCore.Cookies
cookie with expiration date of 10 days later. But after about 30 minutes, the user is logged out. How to force the authenticated user to stay logged in, even after the browser is closed?
IdleTimeout
set to 30 minutes... Either way. can you share yourValidatePrincipal
method too please (if you have overriden that)? – EyotValidatePrincipal
in forums which suggest solutions or tut this type of authentication. Should I implement it? – Sophersync
auth with backend... I thought you might have an issue in there... If you haven't overriden it then you are fine ;-) – Eyot