I am using an open id connect identity provider for my Blazor wasm application and would like an access token to be attached to the http client as described in this article.
However, whenever I create the http client and try to use it I am getting an AccessTokenNotAvailableException, even when logged in.
Here is what I have:
In Program.cs
// Add service for CustomAuthorizationMessageHandler
builder.Services.AddScoped<CustomAuthorizationMessageHandler>();
// Http client for requests to API
builder.Services.AddHttpClient("API", client =>
{
// Set base address to API url
client.BaseAddress = new Uri("https://localhost:44370");
// Set request headers to application/json
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
}).AddHttpMessageHandler<CustomAuthorizationMessageHandler>();
// Auth0 authentication setup
builder.Services.AddOidcAuthentication(options =>
{
builder.Configuration.Bind("Auth0", options.ProviderOptions);
options.ProviderOptions.ResponseType = "code";
});
CustomAuthorizationHandler.cs
public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
{
public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,
NavigationManager navigationManager)
: base(provider, navigationManager)
{
ConfigureHandler(
authorizedUrls: new[] { "https://localhost:44370" },
scopes: new[] { "admin" });
}
}
When trying to access the api
try
{
var client = ClientFactory.CreateClient("API");
message = await client.GetStringAsync("api/message");
}
catch (AccessTokenNotAvailableException e)
{
message = "You CANNOT access the api. Please log in";
}
Currently, the below code works to get the message from the api when removing the AddHttpMessageHandler call in Program.cs but I don't want to have to get the access token every time I make an api call. TokenProvider is of type IAccessTokenProvider and is injected in.
var client = ClientFactory.CreateClient("API");
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, "api/message"))
{
var tokenResult = await TokenProvider.RequestAccessToken();
if (tokenResult.TryGetToken(out var token))
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Value);
var response = await client.SendAsync(requestMessage);
if(response.IsSuccessStatusCode)
{
message = await response.Content.ReadFromJsonAsync<string>();
}
else
{
message = await response.Content.ReadAsStringAsync();
}
}
else
{
message = "You CANNOT access the api. Please log in";
}
}
How can I fix this so I don't get an AccessTokenNotAvailableException every time?