Issue with authentication in Blazor

I am working with Blazor authentication. I have implemented a way to authenticate a user through an API controller that signs in the user and returns the current state of the user with http requests.

The issue is after 2 or less minutes, the cookie expires or something happens that signs out the user.

I still don’t know the issue.

This is the code of the custom authenticate state provider:

using System.Net;
using System.Net.Http.Json;
using System.Security.Claims;
using Domains.Users;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Implementations.Users;

public interface IAccountService
{
     public Task<LoginResponse> Login(string email, string password);
     public Task<bool> Logout();
}

public class CustomAuthenticationStateProvider : AuthenticationStateProvider,IAccountService
{
    private bool _authenticated = false;

    private readonly ClaimsPrincipal Unauthenticated =
        new(new ClaimsIdentity());
    
    private readonly HttpClient _httpClient;
    private readonly NavigationManager NavigationManager;

    public CustomAuthenticationStateProvider(IHttpClientFactory httpClientFactory,NavigationManager manager)
    {
        _httpClient = httpClientFactory.CreateClient("Auth");
        NavigationManager = manager;
    }

    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        _authenticated = false;

        var user = Unauthenticated;
        
        try
        {
            var response = await _httpClient.GetAsync($"{NavigationManager.BaseUri}api/CurrentUser");

            if (response.IsSuccessStatusCode && response.StatusCode == HttpStatusCode.OK)
            {
                var currentUser = await response.Content.ReadFromJsonAsync<User>();

                if (currentUser != null)
                {
                    List<Claim> claims = new List<Claim>();
                    claims.Add(new Claim("UserEmail", currentUser.userEmail));
                    claims.Add(new Claim("UserId", currentUser.userId));
                    claims.Add(new Claim("UserStatus", ((int)currentUser.userStatus).ToString()));

                    foreach (var role in currentUser.userRoles)
                    {
                        var claim = new Claim(ClaimTypes.Role, role.roleType);
                        claim.Properties["ClaimId"] = role.roleId;
                        claims.Add(claim);
                    }

                    var claimsIdentity = new ClaimsIdentity(claims, nameof(CustomAuthenticationStateProvider));
                    
                    user = new ClaimsPrincipal(claimsIdentity);
                } 
            }
            else
            {
                Console.WriteLine($"Failed to retrieve user: {response.ReasonPhrase}");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            throw;
        }
        
        return new AuthenticationState(user);
    }

    public async Task<LoginResponse> Login(string email, string password)
    {
        try
        {
            var user = new UserModel()
            {
                userEmail = email,
                userPassword = password,
            };
            
            var response = await _httpClient.PostAsJsonAsync($"{NavigationManager.BaseUri}api/login", user);

            if (response.IsSuccessStatusCode && response.StatusCode == HttpStatusCode.OK)
            {
                NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
            }

            if (response.Content == null) 
                return new LoginResponse(false, "Server is Down");
            
            var responseContent = await response.Content.ReadFromJsonAsync<LoginResponse>();

            return responseContent;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    public async Task<bool> Logout()
    {
        try
        {
            var response = await _httpClient.PostAsync($"{NavigationManager.BaseUri}api/logout",null);

            if (response.IsSuccessStatusCode)
            {
                NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
                return true;
            }

            return false;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}

And this is the login API controller:

using System.Security.Claims;
using Domains.Users;
using Implementations.Users;
using Interfaces.Users;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;

namespace Implementations.Controllers;

[Route("/api")]
[ApiController]
public class LoginController:ControllerBase
{
    private readonly IUserService userService;

    public LoginController(IUserService userService)
    {
        this.userService = userService;
    }
    
    [HttpPost]
    [Route("login")]
    public async Task<LoginResponse> Login([FromBody] UserModel user)
    {
        try
        {
           var currentUser = await userService.CheckUserCredentials(user.userEmail,user.userPassword);

            if (currentUser.userStatus == Domains.Users.User.LoginStatus.allowed)
            {
                List<Claim> userClaims = new List<Claim>(new []{
                    new Claim("UserId", currentUser.userId),
                    new Claim("UserEmail", currentUser.userEmail),
                    new Claim("UserStatus", ((int)currentUser.userStatus).ToString())
                });
                
                var userRoles = await userService.GetUserRoles(currentUser.userId);
                
                foreach (var role in userRoles)
                {
                   var claim = new Claim(ClaimTypes.Role, role.roleType);
                   claim.Properties["ClaimId"] = role.roleId;
                   
                   userClaims.Add(claim);
                }
                
                var identity = new ClaimsIdentity(userClaims,CookieAuthenticationDefaults.AuthenticationScheme);
                var principal = new ClaimsPrincipal(identity);

                var props = new AuthenticationProperties();
               
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,principal, props);

                var response = new LoginResponse(true, "login successful");

                return response;
            }
            
            if (currentUser.userStatus == Domains.Users.User.LoginStatus.blocked)
            {
                return new LoginResponse(false, "user blocked");;
            }
            else if (currentUser.userStatus == Domains.Users.User.LoginStatus.passwordWrong)
            {
                return new LoginResponse(false, "verify password or username ");
            }
        }
        catch (Exception e)
        {
            return new LoginResponse(false, "issue while login");
        }

        return new LoginResponse(false,"issue while login");
    }
    
    [HttpPost]
    [Route("logout")]
    public async Task<IActionResult> Logout()
    {
        if (HttpContext.User.Identity.IsAuthenticated)
        {
            await HttpContext.SignOutAsync();
            return Ok();
        }

        return BadRequest("No user is currently logged in");
    }
    
    [HttpGet]
    [Route("CurrentUser")]
    public User GetCurrentUser()
    {
        if (HttpContext == null || HttpContext.User == null) 
            return null;
            
        if (HttpContext.User.Identity.IsAuthenticated)
        {
           var authCookie = HttpContext.Request.Cookies["IB"];

           var user= HttpContext.User;
           var claims= user.Claims.Where(claim => claim.Type.Equals(ClaimTypes.Role));

           List<UserRoles> userRoles = new();
           
           foreach (var claim in claims)
           {
               userRoles.Add(new UserRoles()
               {
                   roleId = claim.Properties["ClaimId"],
                   roleType = claim.Value
               });
           }  
           
           return new User()
           {
               userEmail = user.Claims.FirstOrDefault(claim => claim.Type.Equals("UserEmail")).Value,
               userId = user.Claims.FirstOrDefault(claim => claim.Type.Equals("UserId")).Value,
               userStatus =((Domains.Users.User.LoginStatus)
                   int.Parse(user.Claims.FirstOrDefault(claim => claim.Type.Equals("UserStatus")).Value)),
               userRoles = userRoles
           };
        }
        return null;
    }
}

program.cs:

using Blazored.LocalStorage;
using Blazored.SessionStorage;
using Implementations.CartService;
using Implementations.Users;
using Infrastructure.Users;
using Interfaces.Users;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using UI.Components.DialogBox;
using UI.Pages.Home;
using WebApp.Components;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();
builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();
builder.Services.AddScoped(sp => (IAccountService)sp.GetRequiredService<AuthenticationStateProvider>());

builder.Services.AddHttpClient();
builder.Services.AddControllers();

builder.Services.AddBlazoredLocalStorage();
builder.Services.AddHttpContextAccessor();
builder.Services.AddBlazoredSessionStorage();

builder.Services.AddScoped<IUserStorage,UserStorage>();
builder.Services.AddScoped<IUserService,UserService>();
builder.Services.AddScoped<CartService>();
builder.Services.AddSingleton<DialogService>();

builder.Services.AddAuthorization();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).
    AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,options =>
{
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan=TimeSpan.FromHours(10); 
    options.SlidingExpiration = false;
    options.Cookie.Name = "IB";

    options.Cookie.MaxAge=TimeSpan.FromDays(2);
} );

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    app.UseHsts();
}

app.UseHttpsRedirection();
app.MapControllerRoute("Login", "api/Login");
app.MapControllerRoute("CurrentUser", "api/CurrentUser");
app.UseStaticFiles();
app.UseAntiforgery();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UseCookiePolicy();
app.MapRazorComponents<App>().AddInteractiveServerRenderMode()
    .AddAdditionalAssemblies(typeof(HomePage).Assembly).AddInteractiveServerRenderMode();

app.Run();

Please help me with this

I tried to keep refreshing the page to see if this has anything to do with activity but the issue persisted the authentication state reverts back to unauthenticated without the user logging out after like 1.5minutes to 2 minutes
also there is no cookie with the name “IB” in the application tab in the developer inspect menu

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật