I am a beginner at Blazor. It’s my first project using VS22 Blazor project Server side and I have this code in my page Home.razor :
@page "/"
@using WebReportingO_Grain.Kernel
@using WebReportingO_Grain2.Components.Base
@inject UserAccess CurrentUser
<PageTitle>Page d'accueil</PageTitle>
<div>
<!-- Model.Message-->
</div>
@if (!CurrentUser.IsInRole(TUser.AccessRights.User.ToString()) && !CurrentUser.IsInRole(TUser.AccessRights.Admin.ToString()))
{
<EditForm Model="UserCred" FormName="Login" OnValidSubmit="@Login">
<div class="form-group">
<label for="userName" class="col-form-label col-md-2">Nom d'utilisateur</label>
<div class="col-md-10">
<InputText id="userName" @bind-Value="UserCred.UserName" />
</div>
</div>
<div class="form-group">
<label for="password" class=" col-form-label col-md-2">Mot de passe</label>
<div class="col-md-10">
<InputText id="password" @bind-Value="UserCred.Password" type="password" />
</div>
</div>
<br />
<button type="submit" class="btn btn-primary btn-sm">Connexion</button>
</EditForm>
}
else if (CurrentUser.User != null && CurrentUser.User.Identity != null)
{
...
}
Then in Home.razor.cs :
namespace WebReportingO_Grain2.Components.Pages;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components;
using OnlineAutomation.Tools;
using WebReportingO_Grain.Kernel;
public partial class Home
{
[Inject]
private ILogger<Home>? _logger { get; set; }
[Inject]
private NavigationManager? _navigationManager { get; set; }
[Inject]
private IHttpContextAccessor? _httpContextAccessor { get; set; }
public UserId UserCred { get; set; } = new UserId();
public string? Message { get; set; }
public async Task Login()
{
try
{
_logger!.LogInformation($"Login : {UserCred.UserName}, {UserCred.Password}");
// Vérifier si un nom d'utilisateur et un mot de passe ont été fournis
if (!string.IsNullOrEmpty(UserCred.UserName) && !string.IsNullOrEmpty(UserCred.Password))
{
// Recherche d'un utilisateur correspondant dans la base de données
using DBInterface dbManager = new();
TUser? dbUser = dbManager.GetAllUsers().FirstOrDefault(u => string.Compare(UserCred.UserName, u.Name, true) == 0);
// Vérification du mot de passe
if (dbUser != null && Simple3Des.DecryptString(dbUser.PasswordHash) == UserCred.Password)
{
_logger!.LogInformation("Login de l'utilisateur {user}", dbUser.Name);
List<Claim> claims =
[
new(ClaimTypes.Name, UserCred.UserName),
new(ClaimTypes.Role, dbUser.AccessLevelEnu.ToString())
];
ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
AuthenticationProperties authProperties = new()
{
AllowRefresh = true,
//ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
// The time at which the authentication ticket expires. A
// value set here overrides the ExpireTimeSpan option of
// CookieAuthenticationOptions set with AddCookie.
IsPersistent = true,
// Whether the authentication session is persisted across
// multiple requests. When used with cookies, controls
// whether the cookie's lifetime is absolute (matching the
// lifetime of the authentication ticket) or session-based.
//IssuedUtc = <DateTimeOffset>,
// The time at which the authentication ticket was issued.
//RedirectUri = <string>
// The full path or absolute URI to be used as an http
// redirect response value.
};
_httpContextAccessor!.HttpContext!.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties).Wait();
_navigationManager!.NavigateTo("/");
}
}
}
catch (Exception ex)
{
_logger!.LogError("Erreur dans {methodName} : {exceptionType} : {exceptionMessage}", $"{nameof(Home)}.{nameof(Login)}", ex.GetType().Name, ex.Message);
throw;
}
Message = $"Nom d'utilisateur ou mot de passe invalide !";
_navigationManager!.NavigateTo("/");
}
}
public class UserId
{
public string UserName { get; set; } = "";
public string Password { get; set; } = "";
}
The Login function is called but UserCred.User and UserCred.Password are empty (not null).
I don’t understand why the binding (field userName and password) doesn’t work.
Can someone help me, pls?