Home > OS >  The user gets logged out automatically after a particular time even if active
The user gets logged out automatically after a particular time even if active

Time:01-30

On my application user gets logged out automatically after a certain time even if he is active or doing some task. All interactions like insert or update are done by AJAX request. If the user is actively using the application, it would be disruptive for them to be constantly prompted to log in. below I'm sharing the code form csprojand program.cs.

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <BaseOutputPath>D:\Project\Vs Ouput\SMS\bin</BaseOutputPath>
    <BaseIntermediateOutputPath>D:\Project\Vs Ouput\SMS\obj</BaseIntermediateOutputPath>
  </PropertyGroup>

  <ItemGroup>
    <RazorGenerate Include="Views\_ViewImports.cshtml" Link="Views/_ViewImports.cshtml" />
    <Compile Remove="Data\NewFolder\**" />
    <Content Remove="Data\NewFolder\**" />
    <EmbeddedResource Remove="Data\NewFolder\**" />
    <None Remove="Data\NewFolder\**" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Hangfire.AspNetCore" Version="1.7.31" />
    <PackageReference Include="Hangfire.SqlServer" Version="1.7.31" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.10" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.10" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.10" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.10">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.11" />
  </ItemGroup>

  <ItemGroup>
    <None Include="wwwroot\assets\libs\niceselect\js\jquery.nice-select.min.js" />
    <None Include="wwwroot\assets\libs\sweetalert2\sweetalert2.min.js" />
  </ItemGroup>

</Project>

using Hangfire;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using StudentManagement.Data.Interfaces;
using StudentManagement.Data.Repositories;
using StudentManagement.Models;
using StudentManagement.Utilities;

var builder = WebApplication.CreateBuilder(args);

#region Services

builder.Services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(builder.Configuration.GetConnectionString("STDM")));

builder.Services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddTransient<IAccounts, Accounts>();
builder.Services.AddTransient<IInstitutions, Institutions>();
builder.Services.AddTransient<IRoutines, Routines>();
builder.Services.AddTransient<IStudents, Students>();
builder.Services.AddTransient<IPayments, Payments>();
builder.Services.AddTransient<IBooks, Books>();
builder.Services.AddTransient<IContacts, Contacts>();

builder.Services.AddRazorPages();

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "_MyOrigins",
        policy =>
        {
            policy.WithOrigins(.....);
        });
});

builder.Services.AddHangfire(config =>
    config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
    .UseSimpleAssemblyNameTypeSerializer()
    .UseDefaultTypeSerializer()
    .UseSqlServerStorage(builder.Configuration.GetConnectionString("STDM")));
builder.Services.AddHangfireServer();

#endregion

var app = builder.Build();

#region ConfigureApp

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseCors("_MyOrigins");

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});

app.UseHangfireDashboard("/scheduler", new DashboardOptions
{
    Authorization = new[] { new MyAuthorizationFilter() }
});

#endregion

app.Run();

and there's the method for login

[HttpPost]
    [AllowAnonymous]
    public async Task<JsonResult> Login(string email, string password, bool rememberMe)
    {
        Response _response = new()
        {
            message = "Invalid credentials!",
            status = "error",
            flag = 0
        };

        ApplicationUser user = await _userManager.FindByEmailAsync(email);

        if (user != null)
        {
            if (await _userManager.IsInRoleAsync(user, "Manager") == false && await _userManager.IsInRoleAsync(user, "Administrator") == false)
            {
                _response.message = "You are not allowed to log in.";
            }

            var result = await _signInManager.PasswordSignInAsync(email, password, rememberMe, false);

            if (result.Succeeded)
            {
                _response.message = "You've been logged in!";
                _response.status = "success";
                _response.flag = 1;
            }
        }

        return Json(_response);
    }

Now, How can I prevent it from logging out if a user is active? Thank you

CodePudding user response:

Did you look into sliding expiration? This way a cookie gets renewed every time the user interacts with the web server (until the user has not interacted for ExpireTimeSpan and is then forced to login again).

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    }).AddCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
        options.Cookie.MaxAge = options.ExpireTimeSpan; // optional
        options.SlidingExpiration = true;
    });
}

From: https://brokul.dev/authentication-cookie-lifetime-and-sliding-expiration

CodePudding user response:

You could check the offical document, try set as below afer calling AddIdentity:

builder.Services.ConfigureApplicationCookie(options =>
{
    ........
    options.SlidingExpiration = true;
});
  • Related