Сервер
Серверная часть содержит часть входа и контроллеры/конечные точки.

Контроллеры/конечные точки представляют собой минимальные API вот такой
Код: Выделить всё
public static void MapClientEndpoints (this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/api/Client").WithTags(nameof(Client));
group.MapGet("/", async (HypnoContext db) =>
{
return await db.Client.ToListAsync();
})
.RequireAuthorization()
.WithName("GetAllClients")
.WithOpenApi();
}
Код: Выделить всё
builder.Services.AddScoped();
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies();
builder.Services.AddIdentityCore(options =>
options.SignIn.RequireConfirmedAccount = true)
.AddRoles()
.AddEntityFrameworkStores()
.AddSignInManager()
.AddDefaultTokenProviders();
builder.Services
.AddScoped(sp => sp
.GetRequiredService()
.CreateClient("ServerAPI"))
.AddHttpClient("ServerAPI", (provider, client) =>
{
client.BaseAddress = new Uri(builder. Configuration["FrontendUrl"]);
});
Клиентский проект имеет все представления. Представления вызывают API, предоставляемые сервером.

В Program.cs эта конфигурация добавляется «из коробки»:
Код: Выделить всё
builder.Services.AddSingleton();
Код: Выделить всё
string baseEndpoint;
IHttpClientFactory ClientFactory;
HttpClient? httpClient;
public ApiService(string baseUrl, IHttpClientFactory clientFactory)
{
baseEndpoint = baseUrl;
ClientFactory = clientFactory;
httpClient = ClientFactory.CreateClient("ServerAPI");
}
Как защитить API и использовать их на стороне клиента?
Что я пробовал
В Program.cs сервера я добавил этот код для HttpClient:
Код: Выделить всё
builder.Services.AddScoped();
builder.Services.AddHttpClient("ServerAPI", client => {
client.BaseAddress = new Uri(builder.Configuration["FrontendUrl"]);
})
.AddHttpMessageHandler();
builder.Services.AddTransient(sp =>
sp.GetRequiredService().CreateClient("ServerAPI"));
Код: Выделить всё
public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
{
public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,
NavigationManager navigationManager)
: base(provider, navigationManager)
{
ConfigureHandler(
authorizedUrls: new[] { "https://localhost:7241" });
}
}
Код: Выделить всё
@inject HttpClient httpClient
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Get, "/api/Client");
await httpClient.SendAsync(request);
System.AggregateException: «Некоторые службы не может быть
создан (Ошибка при проверке дескриптора службы
'ServiceType: MyApp.CustomAuthorizationMessageHandler
Lifetime: Scoped ImplementationType:
MyApp.CustomAuthorizationMessageHandler': невозможно разрешить
службу для типа
'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider'
при попытке активировать
'MyApp.CustomAuthorizationMessageHandler '.)'

Подробнее здесь: https://stackoverflow.com/questions/792 ... al-account