Getting the auth0 bearer token from .Net Blazor Server app

Hello!
I have 2 sevices, one is a .net core web api, that is protected with auth0 from the quick start sample. The second is a blazor server app, with protection from the auth0 blazor blogpost.

I am trying to get the bearer token from the blazor app so that I can put it in the authorization header of my http client that connects to the web api. The issue is that I can’t find a way to get it.

I’ve tried getting it out of HttpContext via GetToken(“access_token”) but that returns null. I saw some posts mentioning that you should add options to AddOpenIdConnect, but those are only used in .net core 2.1, whereas I am using the new api with AddAuth0WebAppAuthentication. I also tried adding

   .WithAccessToken(options =>
     {
         options.Audience = builder.Configuration["Auth0:Audience"];
     });

from this blogpost Call Protected APIs in ASP.NET Core. But the token still returns as null from httpContext.

How do I get the bearer token from a session so that I can use it when connecting to my web api?

I have the same question. Have you found an answer by any chance?

Did anyone figure this out? Everything else is working except getting the access taken for my Blazor Server App to make calls to my custom API.

Any updates on this?

Same issue here - anyone have an answer to this? Very frustrating trying to get the token passed to the API, as it never has worked.

After beating my head against the wall for 2 days, I found the solution!
In this setup

builder.Services.AddAuth0WebAppAuthentication(options => { })

create new OpenIdConnectEvents

options.OpenIdConnectEvents = new OpenIdConnectEvents { OnTokenValidated = async context => { ... var token = context.TokenEndpointResponse.AccessToken; currentIdentity.AddClaim(new Claim("access_token", token)); ... } }

Be sure to tack on the .WithToken() and add the audience.

Hope this helps someone else.

Wow, didn’t expect an answer for this, thanks!

I’m not sure why there is no clear explanation about how to find this token. Blazor Server should not use the HttpContext (per Microsoft), so all the examples out there do not apply. I think something the .net devs should do is add a token handler to the auth state provider like they do for the web assembly side.

I might also add that if there is a concern about exposure of the token to the client side, you could store in memory instead of claims.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.