Я строю приложение Blazor Server (.net 9, Identity + EntityFramework + Mudblazor). У меня есть пользовательская форма входа в систему, и я хочу аутентифицировать пользователя вручную, используя SigninManager. < /P>
Я использую этот метод для входа в систему: < /p>
private async Task RegoLogin()
{
isBusy = true;
LoginResultRego = true;
try
{
// Try to find the user by email or username
ApplicationUser user = RegoBenutzer.Contains('@')
? await UserManager.FindByEmailAsync(RegoBenutzer)
: await UserManager.FindByNameAsync(RegoBenutzer);
if (user == null)
{
Console.WriteLine("❌ User does not exist.");
LoginResultRego = false;
return;
}
// Step 1: Check if the password is valid (does NOT create authentication cookie)
var result = await SignInManager.CheckPasswordSignInAsync(user, RegoKennwort, lockoutOnFailure: false);
if (result.Succeeded)
{
// Step 2: Perform the actual sign-in (this creates the auth cookie)
await SignInManager.SignInAsync(user, isPersistent: false);
// Step 3: Optionally store user in shared state (if needed)
SharedDataService.LoggedInUser = user;
// Step 4: Conditional redirect
if (user.MustChangePassword)
{
Navigation.NavigateTo("/change-password", forceLoad: true);
}
else
{
Navigation.NavigateTo("/dashboard", forceLoad: true);
}
}
else
{
Console.WriteLine("❌ Invalid login attempt.");
Console.WriteLine($"🔎 Details: IsLockedOut={result.IsLockedOut}, IsNotAllowed={result.IsNotAllowed}, Requires2FA={result.RequiresTwoFactor}");
LoginResultRego = false;
}
}
catch (Exception ex)
{
Console.WriteLine($"❌ Exception occurred during login: {ex.Message}");
LoginResultRego = false;
}
finally
{
isBusy = false;
}
}
< /code>
✅ CheckPassWordSignInasync () return extuced = true, поэтому учетные данные действительны.
❌, но после вызова SignInManager.SigninAsync (...) пользователь все еще не аутентифицирован:
protected pages [Authorize] RedieRive Me Back на страницу Login. AuthenticationStateProvider.
Нет автофиита, кажется, не записано в браузере. устанавливаются через ConfigureApplicationCookie, чтобы иметь /как путь входа.
подтвердил, что user.identity.isauthenticated является ложным после входа.Why doesn't SignInAsync(user, isPersistent: false) set the cookie?
Is there a special requirement to use it inside Blazor Server components?
How can I manually sign in the user and make [Authorize] pages work reliably?
< /code>
setup: < /p>
ASP.NET Core 9
Blazor Server (not WebAssembly)
Entity Framework Core with PostgreSQL
Identity: AddIdentity()
Я строю приложение Blazor Server (.net 9, Identity + EntityFramework + Mudblazor). У меня есть пользовательская форма входа в систему, и я хочу аутентифицировать пользователя вручную, используя SigninManager. < /P> Я использую этот метод для входа в систему: < /p> [code]private async Task RegoLogin() { isBusy = true; LoginResultRego = true;
try { // Try to find the user by email or username ApplicationUser user = RegoBenutzer.Contains('@') ? await UserManager.FindByEmailAsync(RegoBenutzer) : await UserManager.FindByNameAsync(RegoBenutzer);
if (user == null) { Console.WriteLine("❌ User does not exist."); LoginResultRego = false; return; }
// Step 1: Check if the password is valid (does NOT create authentication cookie) var result = await SignInManager.CheckPasswordSignInAsync(user, RegoKennwort, lockoutOnFailure: false);
if (result.Succeeded) { // Step 2: Perform the actual sign-in (this creates the auth cookie) await SignInManager.SignInAsync(user, isPersistent: false);
// Step 3: Optionally store user in shared state (if needed) SharedDataService.LoggedInUser = user;
// Step 4: Conditional redirect if (user.MustChangePassword) { Navigation.NavigateTo("/change-password", forceLoad: true); } else { Navigation.NavigateTo("/dashboard", forceLoad: true); } } else { Console.WriteLine("❌ Invalid login attempt."); Console.WriteLine($"🔎 Details: IsLockedOut={result.IsLockedOut}, IsNotAllowed={result.IsNotAllowed}, Requires2FA={result.RequiresTwoFactor}"); LoginResultRego = false; } } catch (Exception ex) { Console.WriteLine($"❌ Exception occurred during login: {ex.Message}"); LoginResultRego = false; } finally { isBusy = false; } } < /code> ✅ CheckPassWordSignInasync () return extuced = true, поэтому учетные данные действительны. ❌, но после вызова SignInManager.SigninAsync (...) пользователь все еще не аутентифицирован: protected pages [Authorize] RedieRive Me Back на страницу Login. AuthenticationStateProvider. Нет автофиита, кажется, не записано в браузере. устанавливаются через ConfigureApplicationCookie, чтобы иметь /как путь входа. подтвердил, что user.identity.isauthenticated является ложным после входа.Why doesn't SignInAsync(user, isPersistent: false) set the cookie?
Is there a special requirement to use it inside Blazor Server components?
How can I manually sign in the user and make [Authorize] pages work reliably? < /code> setup: < /p> ASP.NET Core 9
Blazor Server (not WebAssembly)
Entity Framework Core with PostgreSQL
Identity: AddIdentity() [/code] Спасибо за вашу помощь!