dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.37k stars 9.99k forks source link

Error retrieving the current token in a Blazor application after successful authentication in Azure B2C with Msal #39311

Closed vsfeedback closed 2 years ago

vsfeedback commented 2 years ago

This issue has been moved from a ticket on Developer Community.


I have created a Blazor application and I use Msal to do authentication following the examples from Azure B2C. With my B2C configuration in the server, I can successfully login, I get the User, the claims and I can call the api. I would need to have access to the token during development to be able to use that token to call my api services directly using swagger. So during Debugging I wanted to print the token on screen to copy and paste.

However, when I try to get the token in the Client after successful login, I get an Exception: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires

This is a very confusing exception and doesn't seem to explain the type of error that is occurring. It seems that is not doing any validation during the parsing or pre-parsing. So not sure why this is happening.

More details:

I initialise with this:

builder. Services.AddMsalAuthentication(options =>
            {
                builder. Configuration.Bind("AzureAdB2C", options. ProviderOptions.Authentication);

//options. ProviderOptions.DefaultAccessTokenScopes.Add("02200220-20202-2020-2020-202020200202002"); // I tried to put the application Id a per documentation and it doesn't work

options. ProviderOptions.DefaultAccessTokenScopes.Add("openid");
                options. ProviderOptions.DefaultAccessTokenScopes.Add("offline_access");

// request scope to access the API
                options. ProviderOptions.AdditionalScopesToConsent.Add("https://myb2c.onmicrosoft.com/whateverApp/MyAPI");

options. ProviderOptions.LoginMode = "redirect";
            });

I also use a custom AuthorizationMessageHandler to be able to call the api, which works well.

However, when in my code I call the code to retrieve the Token, I get the exception + one unhandled exception:

[Inject]
public IAccessTokenProvider TokenProvider { get; set; }
...
var accessTokenResult = await TokenProvider.RequestAccessToken(); // <-- This throws exception

And additionally there is an unhandled exception:

Unhandled Exception:
System.Text.Json.JsonException: Invalid JSON
   at Microsoft.JSInterop.Infrastructure.DotNetDispatcher.EndInvokeJS(JSRuntime jsRuntime, String arguments)
   at Microsoft.AspNetCore.Components.WebAssembly.Services.DefaultWebAssemblyJSRuntime.<>c.<EndInvokeJS> b__7_0(String argsJson)
   at Microsoft.AspNetCore.Components.WebAssembly.Hosting.WebAssemblyCallQueue.Schedule[String](String state, Action`1 callback)
   at Microsoft.AspNetCore.Components.WebAssembly.Services.DefaultWebAssemblyJSRuntime.EndInvokeJS(String argsJson)
Uncaught Error: System.Text.Json.JsonException: Invalid JSONThe thread 0x1b444 has exited with code 0 (0x0).

I have tried in B2C to set the configuration, and I'm able to run the SignIn flow redirecting to jwt.ms passing the token and decoding it.

image.png

And I get the token decoded when redirecting directly to jwt.ms:

image.png


Original Comments

Feedback Bot on 11/12/2021, 00:15 AM:

We have directed your feedback to the appropriate engineering team for further evaluation. The team will review the feedback and notify you about the next steps.


Original Solutions

(no solutions)

mkArtakMSFT commented 2 years ago

Thanks for contacting us. This is already fixed as part of #38962 / https://github.com/dotnet/aspnetcore/pull/39060.

TanayParikh commented 2 years ago

Please note, the fix for this issue should be available in the 6.0.2 patch release.

rmencia-isv commented 2 years ago

Any estimates on this? I've got this installed 6.0.200-preview.21617.4 and still not working

TanayParikh commented 2 years ago

The fix for the underlying System.Text.Json.JsonException: Invalid JSON exception was backported through https://github.com/dotnet/aspnetcore/pull/39075.

@rmencia-isv could you please try this out using the latest installer available at https://github.com/dotnet/installer. Please let us know if you're still having the issue with that, and please provide the exact version of the dotnet sdk being used, along side the exact exception message you're getting.

rmencia-isv commented 2 years ago

I have installed the latest versionfrom the url you provided (dotnet-sdk-6.0.200-preview.22068.4-win-x64.exe) and I still get the same error in Blazor wasm client app.

Checking the list I have this one installed (6.0.200-preview.22068.4) However, by looking at the call stack I see references to Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.1.0*

The error Message: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 73.. See InnerException for more details.

InnerException: at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, Utf8JsonReader& reader, Exception ex)
at System.Text.Json.Serialization.JsonConverter1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.Serialization.JsonConverter1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadCoreAsObject(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore[Object](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.Read[Object](Utf8JsonReader& reader, JsonTypeInfo jsonTypeInfo)
at System.Text.Json.JsonSerializer.Deserialize(Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options)
at Microsoft.JSInterop.JSRuntime.EndInvokeJS(Int64 taskId, Boolean succeeded, Utf8JsonReader& jsonReader)'

TanayParikh commented 2 years ago

by looking at the call stack I see references to Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.1.0*

Ah that's definitely a bit strange. Could you please double check your csproj files to ensure you don't have any hardcoded versions which may be causing this issue? Also, if you could try adding the following to your nuget config:

<add key="dotnet6" value="https://dnceng.pkgs.visualstudio.com/public/_packaging/dotnet6/nuget/v3/index.json" />

Further details here.

rmencia-isv commented 2 years ago

This is what I have in the project file. I also added the nuget in VS to get the packages from that place and no new updates available, even pre-release for any of those packages.

image

image

TanayParikh commented 2 years ago

Hey @rmencia-isv, I took a look at the feeds and you're right the 6.0.2 (prerelease) packages aren't up yet. You can either try waiting for the official 6.0.2 release (mid February), or try the 7.0 alpha packages (not sure if they'll be updated yet though).

rmencia-isv commented 2 years ago

Thanks Tanay for getting back to me. It's unfortunate that the packages are not uploaded yet, as I've seen a number of issues fixed. I'll probably wait for the release next month, if the pre release packages are not updated.

kbeaugrand commented 2 years ago

Hi, @TanayParikh ,

I'm facing the same issue. Unfortunately I cannot wit until mid February. Is there any chance to test the 6.0.2 (prerelease) you mentioned.

This is definitively not present on the repo you suggested...

TanayParikh commented 2 years ago

Hello @kbeaugrand, to test out the pre-release you can try using the nightly SDK & packages as above, or by using the 7.0 alpha/beta packages.

SDK Download: https://github.com/dotnet/installer (ensure you get the 6.0.2 or 7 alpha/beta SDK)

Add to your Nuget config:

<add key="dotnet6" value="https://dnceng.pkgs.visualstudio.com/public/_packaging/dotnet6/nuget/v3/index.json" />

Further details here.

Pete-Nago commented 2 years ago

I also am having the exact same issue with B2C and Blazor WASM. Hope they release the fix soon. I'm hesitant to install preview builds.

kbeaugrand commented 2 years ago

Hi @TanayParikh,

Do you have a more precise date for the release of Microsoft.AspNetCore.Components.WebAssembly.Authentication v6.0.2 ?

Thank you.

TanayParikh commented 2 years ago

Hi @TanayParikh,

Do you have a more precise date for the release of Microsoft.AspNetCore.Components.WebAssembly.Authentication v6.0.2 ?

Thank you.

It was just released earlier today!

kbeaugrand commented 2 years ago

Hi @TanayParikh, Do you have a more precise date for the release of Microsoft.AspNetCore.Components.WebAssembly.Authentication v6.0.2 ? Thank you.

It was just released earlier today!

Thank you for your answer. I checked it, but unfortunately I'm still facing the issue... ;(

TanayParikh commented 2 years ago

unfortunately I'm still facing the issue

To confirm you've updated the SDK/.csproj to utilize the new 6.0.2 packages, correct? What exact error message are you seeing?

Can you please provide a minimal, public, github repro which reproduces this issue?

kbeaugrand commented 2 years ago

unfortunately I'm still facing the issue

To confirm you've updated the SDK/.csproj to utilize the new 6.0.2 packages, correct? What exact error message are you seeing?

Can you please provide a minimal, public, github repro which reproduces this issue?

Hi,

Yes I confirm that I updated my package to 6.0.2 (https://github.com/CGI-FR/IoT-Hub-Portal/blob/main/src/AzureIoTHub.Portal/Client/AzureIoTHub.Portal.Client.csproj). I'm using OpenID connect.

You can find a public repos (not minimal) with my configuration here: https://github.com/CGI-FR/IoT-Hub-Portal/.

For the code sample, that is relevant, you can find at client Program.cs file the executed configuration: https://github.com/CGI-FR/IoT-Hub-Portal/blob/main/src/AzureIoTHub.Portal/Client/Program.cs.

The error message obtained is:


crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 170.. See InnerException for more details.
Microsoft.JSInterop.JSException: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 170.. See InnerException for more details.
 ---> System.Text.Json.JsonException: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 170.
 ---> System.InvalidOperationException: Cannot get the value of a token type 'Null' as a string.
   at System.Text.Json.Utf8JsonReader.TryGetDateTimeOffset(DateTimeOffset& value)
   at System.Text.Json.Utf8JsonReader.GetDateTimeOffset()
   at System.Text.Json.Serialization.Converters.DateTimeOffsetConverter.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1[[System.DateTimeOffset, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessToken, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, AccessToken& value)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessToken, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, AccessToken& value)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessToken, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, InternalAccessTokenResult& value)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, InternalAccessTokenResult& value)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, Utf8JsonReader& reader, Exception ex)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadCoreAsObject(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore[Object](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.Read[Object](Utf8JsonReader& reader, JsonTypeInfo jsonTypeInfo)
   at System.Text.Json.JsonSerializer.Deserialize(Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options)
   at Microsoft.JSInterop.JSRuntime.EndInvokeJS(Int64 taskId, Boolean succeeded, Utf8JsonReader& jsonReader)
   --- End of inner exception stack trace ---
   at Microsoft.JSInterop.JSRuntime.<InvokeAsync>d__16`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].MoveNext()
   at Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationService`3.<RequestAccessToken>d__22[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationState, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteUserAccount, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[Microsoft.AspNetCore.Components.WebAssembly.Authentication.OidcProviderOptions, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].MoveNext()
   at Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__13`1[[AzureIoTHub.Portal.Shared.Models.Device.DeviceListItem[], AzureIoTHub.Portal.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
   at AzureIoTHub.Portal.Client.Pages.Devices.DeviceListPage.LoadDevices() in C:\Users\beaugrandk\Source\Repos\CGI-FR\IoT-Hub-Portal\src\AzureIoTHub.Portal\Client\Pages\Devices\DeviceListPage.razor:line 179
   at AzureIoTHub.Portal.Client.Pages.Devices.DeviceListPage.OnInitializedAsync() in C:\Users\beaugrandk\Source\Repos\CGI-FR\IoT-Hub-Portal\src\AzureIoTHub.Portal\Client\Pages\Devices\DeviceListPage.razor:line 163
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
window.Module.s.printErr @ blazor.webassembly.js:1```
kbeaugrand commented 2 years ago

I may be able to reproduce the issue on a minimal project if needed.

TanayParikh commented 2 years ago

I may be able to reproduce the issue on a minimal project if needed.

Yes please, that'd be much appreciated!

Thanks for the stack trace. I see the underlying System.Text.Json.JsonException: Invalid JSON is resolved (via backported https://github.com/dotnet/aspnetcore/pull/39075), but we still have the

Microsoft.JSInterop.JSException: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 170.. See InnerException for more details.
 ---> System.Text.Json.JsonException: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 170.
 ---> System.InvalidOperationException: Cannot get the value of a token type 'Null' as a string.

error. Re-opening this issue.

kbeaugrand commented 2 years ago

I may be able to reproduce the issue on a minimal project if needed.

Yes please, that'd be much appreciated!

Thanks for the stack trace. I see the underlying System.Text.Json.JsonException: Invalid JSON is resolved (via backported #39075), but we still have the

Microsoft.JSInterop.JSException: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 170.. See InnerException for more details.
 ---> System.Text.Json.JsonException: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 170.
 ---> System.InvalidOperationException: Cannot get the value of a token type 'Null' as a string.

error. Re-opening this issue.

I'll send you the sample app as soon I've pushed on a public repos.

syska commented 2 years ago

I was so happy when I saw this should have been fixed.

Guess I will have to wait a little more with the auth implementation.

kbeaugrand commented 2 years ago

Hi @mkArtakMSFT @TanayParikh ,

I saw that nothing changed here (and I forget to push the sample repository).

This is available herehttps://github.com/kbeaugrand/SampleOpenIDConnect

I'm using Okta identity provider, the settings are present at Program.cs#L16-21

TanayParikh commented 2 years ago

This is available herehttps://github.com/kbeaugrand/SampleOpenIDConnect

Hi @kbeaugrand, could you please confirm the Repo is still available and is public? I'm getting a 404 when I try to access that URL.

image
kbeaugrand commented 2 years ago

My bad, it was private. Now it should be ok

TanayParikh commented 2 years ago

Thanks. Looks like it's an issue with the deserialization of the DateTimeOffset of the AccessToken here:

https://github.com/dotnet/aspnetcore/blob/ce10dcaa31b254bda5dcf854f5578f78418d412c/src/Components/WebAssembly/WebAssembly.Authentication/src/Models/AccessToken.cs#L16-L19

which is a part of

https://github.com/dotnet/aspnetcore/blob/ce10dcaa31b254bda5dcf854f5578f78418d412c/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/RemoteAuthenticationService.cs#L246-L252

which gets called here:

https://github.com/dotnet/aspnetcore/blob/24280d974f0624002f963ef8607afe749f9d1b3e/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/RemoteAuthenticationService.cs#L151

on the client side, this translates to:

https://github.com/dotnet/aspnetcore/blob/24280d974f0624002f963ef8607afe749f9d1b3e/src/Components/WebAssembly/Authentication.Msal/src/Interop/AuthenticationService.ts#L111-L123

which doesn't define AccessToken.Expires, which may be why the deserialization is failing.


For the non-MSAL case:

on the client side, this translates to:

https://github.com/dotnet/aspnetcore/blob/24280d974f0624002f963ef8607afe749f9d1b3e/src/Components/WebAssembly/WebAssembly.Authentication/src/Interop/AuthenticationService.ts#L98-L130

which gets the Expires via:

https://github.com/dotnet/aspnetcore/blob/24280d974f0624002f963ef8607afe749f9d1b3e/src/Components/WebAssembly/WebAssembly.Authentication/src/Interop/AuthenticationService.ts#L136-L140

Based on this, does Expires really need to be a DateTimeOffset vs. DateTime? cc/ @javiercn

TanayParikh commented 2 years ago

Related: https://stackoverflow.com/a/68565455/17995448

TanayParikh commented 2 years ago

Based on https://docs.microsoft.com/dotnet/standard/datetime/system-text-json-support we may be dealing with non compliant DateTimeOffset values.

Attempting to read non-compliant formats with Utf8JsonReader will cause it to throw a FormatException:

// Unhandled exception. System.FormatException: The JSON value is not in a supported DateTime format.

@kbeaugrand can you please confirm what needs to be done to trigger the exception you're seeing, using the repro you provided? I just end up with an Okta 404 when I try to run your project.

kbeaugrand commented 2 years ago

@TanayParikh,

After configuring the OIDC settings for your tenant, and launching the project with Visual Studio, go to https://localhost:7002/fetchdata, you will have the issue present on log from the broswser developper console.

As a sample, you can verify my id_token that wahs provided by okta:

eyJraWQiOiI1YzlnblA3Wk1qbDY0NzdFTEl1VDlyNUpKYi0zLXhBNi04Q2x6akdWY0RJIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiIwMHU0Zm9xdmp0Rkd3c1lvajVkNyIsIm5hbWUiOiJkZW1vIGRlbW8iLCJsb2NhbGUiOiJlbl9VUyIsInZlciI6MSwiaXNzIjoiaHR0cHM6Ly9kZXYtMDc0NjEzMTAub2t0YS5jb20vb2F1dGgyL2RlZmF1bHQiLCJhdWQiOiIwb2E0Zm9yZTdqcGhLRDlHaTVkNyIsImlhdCI6MTY0OTE4ODc2NSwiZXhwIjoxNjQ5MTkyMzY1LCJqdGkiOiJJRC5vU2FlLVo1YWpjTXI3TW1OS3A5ckZCZVhLZi1uMUZCWG5uSEg1Y1FsTkd3IiwiYW1yIjpbInB3ZCJdLCJpZHAiOiIwMG80Zm0zeGV0NkRYQzVxZjVkNyIsIm5vbmNlIjoiZjU1NGE2ZjY3YTgxNDE3OWJhMzdlZmMxNWJhZDk4NWIiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJrYmVhdWdyYW5kQGdtYWlsLmNvbSIsImdpdmVuX25hbWUiOiJkZW1vIiwiZmFtaWx5X25hbWUiOiJkZW1vIiwiem9uZWluZm8iOiJBbWVyaWNhL0xvc19BbmdlbGVzIiwidXBkYXRlZF9hdCI6MTY0ODY0ODk0NSwiYXV0aF90aW1lIjoxNjQ5MTg4NzY0fQ.aa5Cf5nHAm5QwcMaYgtCbU6Tnsub1H29AO-qtnFyOgzh_gY9oig1TxL-LwjiOB0nbMPODUF1Gkku90pAKql2j-zr5vGIoMN6886ZC8avMQn0ra-L6LFn00M_hNPJdWJCyXk9cUVsfkwoD6lqiiZHDDpuh4b59_R6DtLQl8jXES8i7jWiELLSXhe09tTMZy4COa0W6HxrMp2ahNXi954sFvHjkxZeXkpVrOCRUm0Lhzrm2M-hT2VaJ_YlTC78VUUI3eEOlBDqTCuBqyVrL8Q8IEk1tZs8y_LVsseMVkE6ho6kPCpHHdvc561XtmfvIkpVr4pFT8QIhVb7_Z8Jo6LfAw&state=797a8d10e2e647c09530765137eecd16

Don't worry, this doesn't give access to anything.. ;)

kbeaugrand commented 2 years ago

@TanayParikh

Thanks. Looks like it's an issue with the deserialization of the DateTimeOffset of the AccessToken here:

https://github.com/dotnet/aspnetcore/blob/ce10dcaa31b254bda5dcf854f5578f78418d412c/src/Components/WebAssembly/WebAssembly.Authentication/src/Models/AccessToken.cs#L16-L19

which is a part of

https://github.com/dotnet/aspnetcore/blob/ce10dcaa31b254bda5dcf854f5578f78418d412c/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/RemoteAuthenticationService.cs#L246-L252

which gets called here:

https://github.com/dotnet/aspnetcore/blob/24280d974f0624002f963ef8607afe749f9d1b3e/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/RemoteAuthenticationService.cs#L151

on the client side, this translates to:

https://github.com/dotnet/aspnetcore/blob/24280d974f0624002f963ef8607afe749f9d1b3e/src/Components/WebAssembly/Authentication.Msal/src/Interop/AuthenticationService.ts#L111-L123

which doesn't define AccessToken.Expires, which may be why the deserialization is failing.

For the non-MSAL case:

on the client side, this translates to:

https://github.com/dotnet/aspnetcore/blob/24280d974f0624002f963ef8607afe749f9d1b3e/src/Components/WebAssembly/WebAssembly.Authentication/src/Interop/AuthenticationService.ts#L98-L130

which gets the Expires via:

https://github.com/dotnet/aspnetcore/blob/24280d974f0624002f963ef8607afe749f9d1b3e/src/Components/WebAssembly/WebAssembly.Authentication/src/Interop/AuthenticationService.ts#L136-L140

Based on this, does Expires really need to be a DateTimeOffset vs. DateTime? cc/ @javiercn

I think this doesn't comes from the deserialization of the access_token. In my configuration I only get the ID Token from the IDP. The issue occurs while getting the access token. at that time I have no network requests from the browser...

syska commented 2 years ago

From the Blazor WASM when calling var tokenRequest = await TokenProvider.RequestAccessToken(); i get the following error:

 blazor.webassembly.js:1 

       crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 73.. See InnerException for more details.
Microsoft.JSInterop.JSException: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 73.. See InnerException for more details.
 ---> System.Text.Json.JsonException: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 73.
 ---> System.InvalidOperationException: Cannot get the value of a token type 'Null' as a string.
   at System.Text.Json.Utf8JsonReader.TryGetDateTimeOffset(DateTimeOffset& value)
   at System.Text.Json.Utf8JsonReader.GetDateTimeOffset()
   at System.Text.Json.Serialization.Converters.DateTimeOffsetConverter.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1[[System.DateTimeOffset, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessToken, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, AccessToken& value)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessToken, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, AccessToken& value)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessToken, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, InternalAccessTokenResult& value)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, InternalAccessTokenResult& value)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, Utf8JsonReader& reader, Exception ex)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadCoreAsObject(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore[Object](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.Read[Object](Utf8JsonReader& reader, JsonTypeInfo jsonTypeInfo)
   at System.Text.Json.JsonSerializer.Deserialize(Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options)
   at Microsoft.JSInterop.JSRuntime.EndInvokeJS(Int64 taskId, Boolean succeeded, Utf8JsonReader& jsonReader)
   --- End of inner exception stack trace ---
   at Microsoft.JSInterop.JSRuntime.<InvokeAsync>d__16`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].MoveNext()
   at Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationService`3.<RequestAccessToken>d__22[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationState, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteUserAccount, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[Microsoft.Authentication.WebAssembly.Msal.Models.MsalProviderOptions, Microsoft.Authentication.WebAssembly.Msal, Version=6.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].MoveNext()
   at BforBoat.Web.Pages.Profile.OnInitializedAsync() in C:\Projects\vsts\mikaelsyska\bforboat\src\BforBoat.Web\Pages\Profile.razor.cs:line 29
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

image

( If, I can include the actual response from the IDP )

This is the response returned from Azure B2C ...

abbasl7 commented 2 years ago

Do we have any known workaround to handle this issue till it is officially fixed?

kbeaugrand commented 2 years ago

Do we have any known workaround to handle this issue till it is officially fixed?

Unfortunatly not at this time... ;(

SariDev commented 2 years ago

I'm affected by this issue too.

Would be nice if this could be scheduled into one of the next releases.

dougclutter commented 2 years ago

Using 6.0.4 and I'm affected by this issue too. Any timeline on a fix?

andrewwilkin commented 2 years ago

The symptoms I'm getting is after being redirected back from Azure AD B2C, I can see the token being sent, from login-callback the app then moves to login-fail.

Yet the app then seems to then try refreshing a couple of times.

Some of the API calls work then it falls over on the third one with a 401.

Is this a symptom of the same issue?

kbeaugrand commented 2 years ago

@mkArtakMSFT @TanayParikh any update ?

javiercn commented 2 years ago

@kbeaugrand we are looking into it, but it seems the issue happens when the app is not requesting an access token.

kbeaugrand commented 2 years ago

@kbeaugrand we are looking into it, but it seems the issue happens when the app is not requesting an access token.

Thank you @javiercn, Is there a workaround ?

javiercn commented 2 years ago

@kbeaugrand You can likely avoid this issue if you request an access token for the app.

Alternatively you can provide your own JS based on https://github.com/dotnet/aspnetcore/blob/main/src/Components/WebAssembly/Authentication.Msal/src/Interop/AuthenticationService.ts and adapt it to your needs.

kbeaugrand commented 2 years ago

@javiercn ,

The first option suggest to use Hybrid flow (using token response type) right ? Otherwise, since we have the authorization code on the WebAssembly, you suggest to request ourselves the access token ?

To clarify that, I guess that this should be the responsibility of the TokenProvider to do correctly the second option, right ?

SariDev commented 2 years ago

@javiercn regarding your workaround suggestions:

You can likely avoid this issue if you request an access token for the app.

In a Blazor Web Assembly applicaton based on .NET 6.0.4 I try to request a access token like this and it throws a exception as mentioned by @syska

var accessTokenResult = await _tokenProvider.RequestAccessToken(); // <-- This throws exception

_tokenProvider is of type Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider

Unhandled exception rendering component: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 73.. See InnerException for more details.
Microsoft.JSInterop.JSException: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 73.. See InnerException for more details.
 ---> System.Text.Json.JsonException: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 73.
 ---> System.InvalidOperationException: Cannot get the value of a token type 'Null' as a string.
   at System.Text.Json.Utf8JsonReader.TryGetDateTimeOffset(DateTimeOffset& value)
   at System.Text.Json.Utf8JsonReader.GetDateTimeOffset()
   at System.Text.Json.Serialization.Converters.DateTimeOffsetConverter.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1[[System.DateTimeOffset, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessToken, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, AccessToken& value)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessToken, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, AccessToken& value)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessToken, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, InternalAccessTokenResult& value)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, InternalAccessTokenResult& value)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, Utf8JsonReader& reader, Exception ex)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.Serialization.JsonConverter`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].ReadCoreAsObject(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore[Object](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.Read[Object](Utf8JsonReader& reader, JsonTypeInfo jsonTypeInfo)
   at System.Text.Json.JsonSerializer.Deserialize(Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options)
   at Microsoft.JSInterop.JSRuntime.EndInvokeJS(Int64 taskId, Boolean succeeded, Utf8JsonReader& jsonReader)
   --- End of inner exception stack trace ---
   at Microsoft.JSInterop.JSRuntime.<InvokeAsync>d__16`1[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.InternalAccessTokenResult, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].MoveNext()
   at Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationService`3.<RequestAccessToken>d__22[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationState, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteUserAccount, Microsoft.AspNetCore.Components.WebAssembly.Authentication, Version=6.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[Microsoft.Authentication.WebAssembly.Msal.Models.MsalProviderOptions, Microsoft.Authentication.WebAssembly.Msal, Version=6.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]].MoveNext()
   at SariDev.LetsEat.LetsEat.App.Shared.MainLayout.GetAllAsync() in C:\WS_Private\GitHub\SariDev\LetsEat\Code\Applications\LetsEat\LetsEat.App\Shared\MainLayout.razor:line 50
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at MudBlazor.MudBaseButton.OnClickHandler(MouseEventArgs ev)
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

Or do you mean to retrieve the access token in another way? Can you clarify that a bit?


Regarding

Alternatively you can provide your own JS based on https://github.com/dotnet/aspnetcore/blob/main/src/Components/WebAssembly/Authentication.Msal/src/Interop/AuthenticationService.ts and adapt it to your needs.

Has anyone here tried that and had success with it?

kbeaugrand commented 2 years ago

@SariDev unfortunately I didn't understand correctly what is expected to be the correct solution. The suggested workaround doesn't seem clear for me. Furthermore, I cannot understand why this issue is taking so much time since it's a blocking point for integrating Blazor WebAssembly with OpenID Connect...

SariDev commented 2 years ago

@kbeaugrand same for me.

Maybe someone can clarify how those workarounds should be implemented with more details.

Furthermore, I cannot understand why this issue is taking so much time since it's a blocking point for integrating Blazor WebAssembly with OpenID Connect..

I'm also suprises by this. One would expect that this is a heavily requested Feature and that it should work without issues

javiercn commented 2 years ago

@kbeaugrand here is a sample that shows how you can customize the JS we provide. It uses MSAL, but the steps are equivalent for OpenID Connect.

https://github.com/javiercn/BlazorWasmMsalSample

andrewwilkin commented 2 years ago

Looking at the sample: interface AccessToken { value: string; expires: Date | null; grantedScopes: string[]; }

I presume from the error previously that the AccessToken has null expiry and thus cannot be converted to the DateTimeOffset by the serializer: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 73.. See InnerException for more details. Microsoft.JSInterop.JSException: An exception occurred executing JS interop: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 73.. See InnerException for more details. ---> System.Text.Json.JsonException: The JSON value could not be converted to System.DateTimeOffset. Path: $.token.expires | LineNumber: 0 | BytePositionInLine: 73. ---> System.InvalidOperationException: Cannot get the value of a token type 'Null' as a string.

Maybe it is line 164/165: const result = await this.signInCore(request); if (!result) { return this.redirect(); } else if (this.isMsalError(result)) { return this.error(result.errorMessage); }

If the result contains something then it won't make the call on line 166. Not tried debugging it yet, thoughts?

ghost commented 2 years ago

Thanks for contacting us.

We're moving this issue to the .NET 7 Planning milestone for future evaluation / consideration. We would like to keep this around to collect more feedback, which can help us with prioritizing this work. We will re-evaluate this issue, during our next planning meeting(s). If we later determine, that the issue has no community involvement, or it's very rare and low-impact issue, we will close it - so that the team can focus on more important and high impact issues. To learn more about what to expect next and how this issue will be handled you can read more about our triage process here.

Spaceman1861 commented 2 years ago

If it helps anyone here is how I implemented a work around for this.

I needed to get the token to pass it to my API.

I added this to the index.html

<script>
    window.getJWT = () => JSON.parse(sessionStorage[
        Object
            .keys(sessionStorage)
            .find(_ => _.includes("yourdomain.b2clogin.com-idtoken"))
        ])
        .secret;
</script>

Then commented out the recommended message handler:

builder.Services.AddHttpClient(
    "WebAPI",
    (services,client) => {
        client.BaseAddress = new Uri("http://localhost:7071");
    }
);
// COMMENT THIS OUT
//.AddHttpMessageHandler<CustomAuthorizationMessageHandler>();

builder
    .Services
    .AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
    .CreateClient("WebAPI"));

Then when you use the Httpclient manually add it:

    [Inject]
    protected HttpClient? Http { get; set; }

    [Inject]
    protected IJSRuntime JS { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (Http == null)
            throw new ArgumentNullException(nameof(Http));

        if (JS == null)
            throw new ArgumentNullException(nameof(JS));

        var text = await JS.InvokeAsync<string>("getJWT", new object[] { });

        Http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
            "Bearer",
            text
        );

        using var stream = await Http.GetAsync("http://localhost:7071/api/Function1");

    }

Its pretty janky but works for me until they roll out a fix :).

kbeaugrand commented 2 years ago

@Spaceman1861, this would add the id_token in the Authorization header, right ? In that case, I guess the authentication should not pass to the backend since this is not the access_token for your backend audience...

Spaceman1861 commented 2 years ago

Perhaps I'm looking at it wrong @kbeaugrand ill walk you through the train of though if you think I have it wrong id love to know:

kbeaugrand commented 2 years ago

@Spaceman1861

Can you print in the discussion, the tokens you have in the session storage (not the values, just the keys) ? Maybe I miss understand the OAuth 2.0 (and OpenId protocol), but with the AspNetCore Assembly, I can only work with the id_token. To my standing point, my WebAssembly App should be considered as a client app, and should act to my API on behalf of the user. So my API refuse the id_token as the Bearer token because it has been issued for identification, not for authorization....

image Source: https://auth0.com/blog/id-token-access-token-what-is-the-difference/.

@javiercn, I cannot understand the decision to move the fix to this issue to .NET 7. What is the solution to use WebAssembly Authenticated (even in MSAL or OpenIdConnect) and provide the access token to the API part properly ?

I have two issues :

These two issues makes the Blazor WebAssembly not usable with an authenticated resource !