I am not able to implement a working authentication system in my Blazor .NET8 ServerInteractive application. I am quite new at web dev (I am more of a WinForm/WPF programmer)
I have search internet for now more that a full day but I can’t figure out how to do it properly ans simply.
At the moment, I have kind of a working authentication but not “persistent”. I have implemented a custom AuthenticationStateProvider like this :
public class AuthenticationManager(ILogger<AuthenticationManager> logger) : AuthenticationStateProvider
{
private ClaimsPrincipal _user = new();
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
return Task.FromResult(new AuthenticationState(_user));
}
public ClaimsPrincipal? LogInUser(string decryptedName, string decryptedPassword)
{
try
{
// Vérifier si un nom d'utilisateur et un mot de passe ont été fournis
if (!string.IsNullOrEmpty(decryptedName) && !string.IsNullOrEmpty(decryptedPassword))
{
// Recherche d'un utilisateur correspondant dans la base de données
using DBInterface dbManager = new();
TUser? dbUser = dbManager.GetAllUsers().FirstOrDefault(u => string.Compare(decryptedName, u.Name, true) == 0);
// Vérification du mot de passe
if (dbUser != null && Simple3Des.DecryptString(dbUser.PasswordHash) == decryptedPassword)
{
List<Claim> claims =
[
new(ClaimTypes.Name, decryptedName),
new(ClaimTypes.Role, dbUser.AccessLevelEnu.ToString())
];
ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
_user = new(claimsIdentity);
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
return _user;
}
}
}
catch (Exception ex)
{
logger!.LogError("Erreur dans {methodName} : {exceptionType} : {exceptionMessage}", $"{nameof(AuthenticationManager)}.{nameof(LogInUser)}", ex.GetType().Name, ex.Message);
throw;
}
return null;
}
public void LogOutUser()
{
_user = new();
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
}
The login/logout is working, I can even navigate in my website and the user is retained but if I refresh the page (F5) or open a new tab the user is not logged any more. I do understand is normal because of the way my user is stored (private field of AuthenticationManager).
Now, the question is : how to make it work as expected?
I am quite sure it doesn’t require much more but I am stuck…