2

I have a Blazor serverside application. To authenticate against it I have Azure AD B2C. I need to grab the access token (JWT) to authenticate against an API.

I have tried many possible answers of which none is working. The most common one is to use await httpContext.GetTokenAsync("access_token"); (or "id_token").

For me in blazor this always returns null. If I try this in a demo asp.net API, the GetTokenAsync returns the correct JWT for me.

In my Blazor program.cs I have

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureB2C"));

I have also tried to use AddOpenIdConnect with savetoken=true

Questions are:

  1. How do I get the token in a blazor serverside app?
  2. What in my startup am I missing?

P.S. Also tried:

builder.Services.AddAuthentication(opt =>
{
    opt.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    opt.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
}).AddCookie().AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.Authority = builder.Configuration.GetSection("Authority").Value;;
    options.ClientId = builder.Configuration.GetSection("ClientId").Value;
    options.SaveTokens = true;
});

[EDIT] I have also tried the solution as described here https://learn.microsoft.com/en-us/aspnet/core/blazor/security/server/additional-scenarios?view=aspnetcore-6.0 and this also return null to me, even after I added savetoken = true

  • HttpContext is a bit of tricky in Blazor. Try accessing it within the .cshtml file which holds your blazor app. – Marvin Klein Aug 16 '22 at 13:00
  • 1
    @MarvinKlein thanks, I tried that as well. That also returned null for me. I also went and setup more in DI with AddJwtBearer with save token and this also did not help. – Laurent Greyling Aug 16 '22 at 19:03

0 Answers0