Проблема со входом в серверное приложение ASP.NET Core 8.0 BlazorC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Гость
 Проблема со входом в серверное приложение ASP.NET Core 8.0 Blazor

Сообщение Гость »


Я пишу серверное приложение Blazor ASP.NET Core 8.0. Я использую Microsoft Identity Framework Core для авторизации. Он загружает пункты меню только после успешного входа пользователя в систему. Я использовал следующий сценарий авторизации на обоих

Код: Выделить всё

NavMenu.razor
and

Код: Выделить всё

Home.razor
components.

Код: Выделить всё


........







When app loads, it asks for login. At successful login, it displays the menu items in the . Когда я выполняю операцию отправки на любой из страниц, все пункты меню исчезают и снова отображается страница входа.
Вот моя

Код: Выделить всё

program.cs
code:

Код: Выделить всё

using GetTutorsOnline.Components;
using GetTutorsOnline.Components.Account;
using GetTutorsOnline.Data;
using GTO.IModels.IModelRepos;
using GTO.Infrastructure.Data;
using GTO.Infrastructure.Repositories;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorComponents().AddInteractiveServerComponents();

builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();

builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies();

var conStr = builder.Configuration.GetConnectionString("DifriPediaSQLDb");
builder.Services.AddDbContextFactory(options => options.UseSqlServer(conStr));
builder.Services.AddDbContext(options => options.UseSqlServer(conStr));

builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddIdentityCore(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores()
.AddSignInManager()
.AddDefaultTokenProviders();

builder.Services.AddSingleton();

builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();

var app = builder.Build();

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

app.UseHttpsRedirection();

app.UseStaticFiles();
app.UseAntiforgery();

//app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapRazorComponents()
.AddInteractiveServerRenderMode();

app.MapAdditionalIdentityEndpoints();

app.Run();
Below is the code of

Код: Выделить всё

IdentityRevalidatingAuthenticationStateProvider
class

Код: Выделить всё

using GetTutorsOnline.Data;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using System.Security.Claims;

namespace GetTutorsOnline.Components.Account
{
// This is a server-side AuthenticationStateProvider that revalidates the security stamp for the connected user
// every 30 minutes an interactive circuit is connected.
internal sealed class IdentityRevalidatingAuthenticationStateProvider(
ILoggerFactory loggerFactory,
IServiceScopeFactory scopeFactory,
IOptions options)
: RevalidatingServerAuthenticationStateProvider(loggerFactory)
{
protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(30);

protected override async Task  ValidateAuthenticationStateAsync(
AuthenticationState authenticationState, CancellationToken cancellationToken)
{
// Get the user manager from a new scope to ensure it fetches fresh data
await using var scope = scopeFactory.CreateAsyncScope();
var userManager = scope.ServiceProvider.GetRequiredService();
return await ValidateSecurityStampAsync(userManager, authenticationState.User);
}

private async Task ValidateSecurityStampAsync(UserManager userManager, ClaimsPrincipal principal)
{
var user = await userManager.GetUserAsync(principal);
if (user is null)
{
return false;
}
else if (!userManager.SupportsUserSecurityStamp)
{
return true;
}
else
{
var principalStamp = principal.FindFirstValue(options.Value.ClaimsIdentity.SecurityStampClaimType);
var userStamp = await userManager.GetSecurityStampAsync(user);
return principalStamp == userStamp;
}
}
}
}



Источник: https://stackoverflow.com/questions/781 ... server-app
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»