AddOidcAuthentication in blazor Web App .net 9

Prathamesh Shende 421 Reputation points
2025-04-30T07:41:07.5866667+00:00

I added the Oidc Authentication in blazor client project but it shows error
IAccessTokenProvider Not Registered.

I want to get the access token into HttpClient as authorization header bearer token.

namespace ClientThree.Client;

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;

public class OidcAuthorizationHandler : DelegatingHandler
{
    private readonly IAccessTokenProvider _tokenProvider;
    private readonly NavigationManager _navigation;

    public OidcAuthorizationHandler(IAccessTokenProvider tokenProvider, NavigationManager navigation)
    {
        _tokenProvider = tokenProvider;
        _navigation = navigation;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var tokenResult = await _tokenProvider.RequestAccessToken(new AccessTokenRequestOptions
        {
            Scopes = ["api"] // Match the scopes your API requires
        });

        if (tokenResult.TryGetToken(out var token))
        {
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Value);
        }
        else
        {
            // Optional: Redirect to login if token is not available
            _navigation.NavigateTo(tokenResult.InteractiveRequestUrl);
            return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        }

        return await base.SendAsync(request, cancellationToken);
    }
}

Program.cs client  

builder.Services.AddOidcAuthentication(options =>
{
    builder.Configuration.Bind("Oidc", options.ProviderOptions);
    options.ProviderOptions.DefaultScopes.Add("api"); // match API required scopes
});
builder.Services.AddHttpClient("ApiClient", httpClient =>
{
    httpClient.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
}).AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

builder.Services.AddScoped(sp => sp.GetService<IHttpClientFactory>().CreateClient("ApiClient"));

builder.Services.AddScoped<IWeatherForecaster, ClientWeatherForecaster>();
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject IAccessTokenProvider TokenProvider
@page "/AccessToken"
@jwtToken
@code {
    string jwtToken;
    protected override async Task OnInitializedAsync()
    {
        var result = await TokenProvider.RequestAccessToken();
        if (result.TryGetToken(out var token))
        {
            jwtToken = token.Value;
            Console.WriteLine(token.Value); // JWT
        }
    }
}

what is the missing in the code?

Blazor Training
Blazor Training
Blazor: A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.Training: Instruction to develop new skills.
31 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Pradeep M 8,185 Reputation points Microsoft External Staff
    2025-04-30T08:30:54.03+00:00

    Hi Prathamesh Shende,

    Thank you for reaching out to Microsoft Q & A forum. 

    The error "IAccessTokenProvider not registered" usually indicates that the OIDC authentication services have not been correctly configured in a Blazor WebAssembly project. 

    To resolve this: 

    1.Ensure the project is a Blazor WebAssembly app, not a Blazor Server or .NET 9 Blazor Web App (which use a different authentication model). 

    2.Verify the required package is installed:  Microsoft.AspNetCore.Components.WebAssembly.Authentication 

    3.Ensure authentication services are registered in Program.cs: 

    builder.Services.AddOidcAuthentication(options =>
    {
        builder.Configuration.Bind("Oidc", options.ProviderOptions);
        options.ProviderOptions.DefaultScopes.Add("api");
    });
    
    

     4.Confirm the OIDC configuration exists in wwwroot/appsettings.json: 

    "Oidc": {
      "Authority": "https://your-auth-server",
      "ClientId": "your-client-id",
      "ResponseType": "code",
      "DefaultScopes": ["openid", "profile", "api"]
    }
    
    

    5.Use BaseAddressAuthorizationMessageHandler when configuring HttpClient to attach the access token automatically. 

    If the project is based on the new .NET 9 Blazor Web App template, please note that it uses a different authentication approach, and IAccessTokenProvider from WebAssembly is not supported in that model.

    If you have found the answer provided to be helpful, please click on the "Accept answer/Upvote" button so that it is useful for other members in the Microsoft Q&A community.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.