Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Configure HttpClient in Blazor with Individual Identity

$
0
0

In my .NET 8 Blazor web application, I use the "Individual Account" to authenticate the users (so I'm using Microsoft Identity). I have a server and a client project. I have some endpoints that I want to protect: the endpoints are minimum APIs in the server project under the folder Controllers. For example,

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();}

In the Program.cs, I added this code for the HttpClient:

builder.Services.AddScoped<CustomAuthorizationMessageHandler>();builder.Services.AddHttpClient("ServerAPI", client => {        client.BaseAddress = new Uri(builder.Configuration["FrontendUrl"]);    })   .AddHttpMessageHandler<CustomAuthorizationMessageHandler>();builder.Services.AddTransient(sp =>    sp.GetRequiredService<IHttpClientFactory>().CreateClient("ServerAPI"));

The CustomAuthorizationMessageHandler is as follows

public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler{    public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,        NavigationManager navigationManager)        : base(provider, navigationManager)    {        ConfigureHandler(           authorizedUrls: new[] { "https://localhost:7241" });    }}

I'm doing this because I want to make calls to the APIs exposed in the server project protected by the Individual Account. So, in a page

@inject HttpClient httpClientHttpRequestMessage request = new HttpRequestMessage(    HttpMethod.Get, "/api/Client");await httpClient.SendAsync(request);

When I run the application, I immediately get an error:

System.AggregateException: 'Some services are not able to beconstructed (Error while validating the service descriptor'ServiceType: MyApp.CustomAuthorizationMessageHandlerLifetime: Scoped ImplementationType:MyApp.CustomAuthorizationMessageHandler': Unable to resolveservice for type'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider'while attempting to activate'MyApp.CustomAuthorizationMessageHandler'.)'

enter image description here

So, I tried to add the following code

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)    .AddJwtBearer(options =>    {        options.TokenValidationParameters = new TokenValidationParameters        {            ValidateIssuer = true,            ValidateAudience = true,            ValidateLifetime = true,            ValidateIssuerSigningKey = true,            ValidIssuer = builder.Configuration["JwtIssuer"],            ValidAudience = builder.Configuration["JwtAudience"],            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(                                   builder.Configuration["JwtSecurityKey"]))        };    });

but this didn't help. What did I miss?


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>