In my Blazor WASM app, I get 401 -Unauthorized status code when I call my backend API using the following code. How do I check to make sure a valid access_token is being attached to my API calls?
Here's Program.cs code:
builder.Services.AddHttpClient("MyApiClient", client => client.BaseAddress = new Uri("https://api.test.com")) .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>() .CreateClient("MyApiClient"));And in my service, I make an API call with this code:
public async Task<User> GetUser(){ // Set URL var url = "/account/info"; var user = await GetAsync<User>(url); return user;}private async Task<T> GetAsync<T>(string url){ if (string.IsNullOrWhiteSpace(url)) return default; using (var client = _httpClientFactory.CreateClient("MyApiClient")) { var result = await client.GetAsync(url); if (!result.IsSuccessStatusCode) throw new Exception("My API GET call failed. URL: " + url); var json = await result.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize<T>(json); }}Do you see anything that doesn't look right here? If not, how can I make sure a valid access_token is being attached to my API calls?
P.S. I see that the HttpClient is created correctly and the BaseAddress is correct in the error message I get. The error message is a standard unauthorized access error. I don't see any additional data in the error message, other than the url is definitely correct.
I also want to mention that I handle identity management and access tokens through Azure AD B2C. That setup seems correct as the user is able to sign in fine and the Id of the user is correct as well.