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