Wanted: Suggestions on Debugging Blazor Server AAD/B2C example

Siegfried Heintze 1,881 Reputation points
2022-02-11T00:30:00.88+00:00

Original Post: Feb 10 2022 at 4:30 PM

I'm having a couple of problems with the Blazor Server calls WebAPI AAD/B2C example.

I'm having some trouble with formatting as as described in this other post.

The subject of this post is soliciting help for getting REST call to the Web API to work.

Authentication with AAD/B2c is working!

So I start the client and server with the "dotnet watch run" commands and the browser pops up and I log in and click the To Do list button and I get this stack trace (see below). As per the instructions, I have installed the phoney (self signed) SSL certificates to allow me to use SSL.

I took care to follow the instructions carefully and exposed the API in the server registration with the access_as_user scope and added API permissions to the client registration in my AAD/B2C tenant in the azure portal. I confirmed that both the blazer server (client) and the REST service are using a scope of "access_as_user" and this matches the scope I defined in the azure portal. As far as I can determine, I have followed the instructions exactly.

How might I proceed to make this REST call work? Below are the stack traces from the log file from the Blazor Server Client and the Browser Devtools console.

Here is the stack trace resulting from "dotnet watch run" for the Blazor server (client):

info: Microsoft.Hosting.Lifetime[0]  
      Content root path: C:\Users\abcxyz\source\repos\ms-identity-blazor-server\WebApp-your-API\B2C\Client  
fail: Microsoft.Identity.Web.TokenAcquisition[0]  
      (False) MSAL 4.24.0.0 MSAL.NetCore Microsoft Windows 10.0.19042 [02/11/2022 00:33:26 - 536c0c2c-9122-46d8-b17d-aa64bd18699e] Exception type: Microsoft.Identity.Client.MsalUiRequiredException  
      , ErrorCode: user_null  
      HTTP StatusCode 0  
      CorrelationId   
        
         at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)  
         at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)  
         at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)  
IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user. See https://aka.ms/ms-id-web/ca_incremental-consent.   
info: System.Net.Http.HttpClient.Default.LogicalHandler[100]  
      Start processing HTTP request POST https://mydomainname.b2clogin.com/tfp/mydomainname.onmicrosoft.com/b2c_1_susi/oauth2/v2.0/token  
info: System.Net.Http.HttpClient.Default.ClientHandler[100]  
      Sending HTTP request POST https://mydomainname.b2clogin.com/tfp/mydomainname.onmicrosoft.com/b2c_1_susi/oauth2/v2.0/token  
info: System.Net.Http.HttpClient.Default.ClientHandler[101]  
      Received HTTP response after 1329.6445ms - OK  
info: System.Net.Http.HttpClient.Default.LogicalHandler[101]  
      End processing HTTP request after 1343.1207ms - OK  
info: System.Net.Http.HttpClient.Default.LogicalHandler[100]  
      Start processing HTTP request POST https://mydomainname.b2clogin.com/tfp/mydomainname.onmicrosoft.com/b2c_1_susi/oauth2/v2.0/token  
info: System.Net.Http.HttpClient.Default.ClientHandler[100]  
      Sending HTTP request POST https://mydomainname.b2clogin.com/tfp/mydomainname.onmicrosoft.com/b2c_1_susi/oauth2/v2.0/token  
info: System.Net.Http.HttpClient.Default.ClientHandler[101]  
      Received HTTP response after 833.7913ms - OK  
info: System.Net.Http.HttpClient.Default.LogicalHandler[101]  
      End processing HTTP request after 834.1218ms - OK  
info: System.Net.Http.HttpClient.ToDoListService.LogicalHandler[100]  
      Start processing HTTP request GET https://localhost:44332/api/todolist  
info: System.Net.Http.HttpClient.ToDoListService.ClientHandler[100]  
      Sending HTTP request GET https://localhost:44332/api/todolist  
The SSL connection could not be established, see inner exception.  
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]  
      An unhandled exception has occurred while executing the request.  
System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.  
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.  
   at System.Net.Security.SslStream.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception)  
   at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.PartialFrameCallback(AsyncProtocolRequest asyncRequest)  
--- End of stack trace from previous location where exception was thrown ---  
   at System.Net.Security.SslStream.ThrowIfExceptional()  
   at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)  
   at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result)  
   at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult)  
   at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__65_1(IAsyncResult iar)  
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)  
--- End of stack trace from previous location where exception was thrown ---  
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)  
   --- End of inner exception stack trace ---  
   at Microsoft.Identity.Web.MicrosoftIdentityConsentAndConditionalAccessHandler.HandleException(Exception exception)  
   at blazorserver_client.Pages.ToDoPages.ToDoListBase.GetToDoListService() in C:\Users\abcxyz\source\repos\ms-identity-blazor-server\WebApp-your-API\B2C\Client\Pages\ToDoPages\ToDoListBase.cs:line 47  
   at blazorserver_client.Pages.ToDoPages.ToDoListBase.OnInitializedAsync() in C:\Users\abcxyz\source\repos\ms-identity-blazor-server\WebApp-your-API\B2C\Client\Pages\ToDoPages\ToDoListBase.cs:line 28  
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()  
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)  
   at Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)  
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)  
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessAsynchronousWork()  
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(Int32 componentId, ParameterView initialParameters)  
   at Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.CreateInitialRenderAsync(Type componentType, ParameterView initialParameters)  
   at Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.RenderComponentAsync(Type componentType, ParameterView initialParameters)  
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.<>c__11`1.<<InvokeAsync>b__11_0>d.MoveNext()  
--- End of stack trace from previous location where exception was thrown ---  
   at Microsoft.AspNetCore.Mvc.ViewFeatures.StaticComponentRenderer.PrerenderComponentAsync(ParameterView parameters, HttpContext httpContext, Type componentType)  
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.PrerenderedServerComponentAsync(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection)  
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.RenderComponentAsync(ViewContext viewContext, Type componentType, RenderMode renderMode, Object parameters)  
   at Microsoft.AspNetCore.Mvc.TagHelpers.ComponentTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)  
   at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, Int32 i, Int32 count)  
   at blazorserver_client.Pages.Pages__Host.<ExecuteAsync>b__14_1() in C:\Users\abcxyz\source\repos\ms-identity-blazor-server\WebApp-your-API\B2C\Client\Pages\_Host.cshtml:line 20  
   at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()  
   at blazorserver_client.Pages.Pages__Host.ExecuteAsync() in C:\Users\abcxyz\source\repos\ms-identity-blazor-server\WebApp-your-API\B2C\Client\Pages\_Host.cshtml:line 5  
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)  
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)  
   at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)  
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)  
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultFilters>g__Awaited|27_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)  
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)  
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)  
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)  
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)  
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)  

Here is the stack trace I found in the Edge DevTools console:

System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.  
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.  
   at System.Net.Security.SslStream.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception)  
   at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)  
   at System.Net.Security.SslStream.PartialFrameCallback(AsyncProtocolRequest asyncRequest)  
--- End of stack trace from previous location where exception was thrown ---  
   at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)  
   at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result)  
   at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult)  
   at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__65_1(IAsyncResult iar)  
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)  
--- End of stack trace from previous location where exception was thrown ---  
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)  
   --- End of inner exception stack trace ---  
   at Microsoft.Identity.Web.MicrosoftIdentityConsentAndConditionalAccessHandler.HandleException(Exception exception)  
   at blazorserver_client.Pages.ToDoPages.ToDoListBase.GetToDoListService() in C:\Users\shein\source\repos\ms-identity-blazor-server\WebApp-your-API\B2C\Client\Pages\ToDoPages\ToDoListBase.cs:line 47  
   at blazorserver_client.Pages.ToDoPages.ToDoListBase.OnInitializedAsync() in C:\Users\shein\source\repos\ms-identity-blazor-server\WebApp-your-API\B2C\Client\Pages\ToDoPages\ToDoListBase.cs:line 28  
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()  
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)  

Sun May 14 2022 Update:

I am now I am getting a different stack trace after successfully authenticating with the client and attempting to get the to do list from the service:

Microsoft.Identity.Web.MicrosoftIdentityConsentAndConditionalAccessHandler.HandleException(Exception exception)  
blazorserver_client.Pages.ToDoPages.ToDoListBase.GetToDoListService() in ToDoListBase.cs  
-  
            }  
            catch (Exception ex)  
            {  
                Console.WriteLine(ex.Message);  
                // Process the exception from a user challenge  
                ConsentHandler.HandleException(ex);  
            }  
        }  
        /// <summary>  
        /// Deletes the selected item then retrieves the todo list.  
        /// </summary>  
blazorserver_client.Pages.ToDoPages.ToDoListBase.OnInitializedAsync() in ToDoListBase.cs  
-  
        protected IEnumerable<ToDo> toDoList = new List<ToDo>();  
          
        protected ToDo toDo = new ToDo();  
         
        protected override async Task OnInitializedAsync()  
        {  
            await GetToDoListService();  
        }  
         
        /// <summary>  
        /// Gets all todo list items.  
        /// </summary>  
        /// <returns></returns>  
Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()  
Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)  
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)  
Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)  
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessAsynchronousWork()  
Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(int componentId, ParameterView initialParameters)  
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.CreateInitialRenderAsync(Type componentType, ParameterView initialParameters)  
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.RenderComponentAsync(Type componentType, ParameterView initialParameters)  
Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext+<>c__11<TResult>+<<InvokeAsync>b__11_0>d.MoveNext()  
Microsoft.AspNetCore.Mvc.ViewFeatures.StaticComponentRenderer.PrerenderComponentAsync(ParameterView parameters, HttpContext httpContext, Type componentType)  
Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.PrerenderedServerComponentAsync(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection)  
Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.RenderComponentAsync(ViewContext viewContext, Type componentType, RenderMode renderMode, object parameters)  
Microsoft.AspNetCore.Mvc.TagHelpers.ComponentTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)  
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count)  
blazorserver_client.Pages.Pages__Host.<ExecuteAsync>b__14_1() in _Host.cshtml  
-  
    <base href="~/" />  
    <link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />  
    <link href="css/site.css" rel="stylesheet" />  
</head>  
<body>  
    <app>  
        <component type="typeof(App)" render-mode="ServerPrerendered" />  
    </app>  
    <div id="blazor-error-ui">  
        <environment include="Staging,Production">  
            An error has occurred. This application may no longer respond until reloaded.  
        </environment>  
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()  
blazorserver_client.Pages.Pages__Host.ExecuteAsync() in _Host.cshtml  
-  
@page "/"  
@namespace blazorserver_client.Pages  
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers  
@{  
    Layout = null;  
}  
<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="utf-8" />  
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)  
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)  
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)  
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)  
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)  
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)  
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)  
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)  
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultFilters>g__Awaited|27_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)  
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)  
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)  
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)  
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)  
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)  
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)  
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)  
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)  
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)  

The REST service did not provide a stack trace... However, the stdout console gave some clues:

Starting WebAPIServiceMainProgram  
Configure Service: begin StartupBlazorServerAADClientCallWebAPI  
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]  
      User profile is available. Using 'C:\Users\shein\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.  
Configure Service: begin StartupBlazorServerAADClientCallWebAPI  
Service: Adding authorization policies  
Service: ReadScope: access_as_user  
warn: Microsoft.AspNetCore.Server.Kestrel[0]  
      Overriding address(es) 'http://localhost:1040/'. Binding to endpoints defined in UseKestrel() instead.  
info: Microsoft.Hosting.Lifetime[0]  
      Now listening on: https://localhost:44332  
info: Microsoft.Hosting.Lifetime[0]  
      Application started. Press Ctrl+C to shut down.  
info: Microsoft.Hosting.Lifetime[0]  
      Hosting environment: Development  
info: Microsoft.Hosting.Lifetime[0]  
      Content root path: c:\Users\shein\source\repos\ms-identity-blazor-server-siegfork\WebApp-your-API\B2C\Service  
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]  
      Request starting HTTP/1.1 GET https://localhost:44332/api/todolist  
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]  
      Authorization failed.  
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12]  
      AuthenticationScheme: Bearer was challenged.  
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]  
      Request finished in 462.7426ms 401  

Interesting: Bearer was challenged! So how does the service confirm the bearer and reject it?

The one change I made was to add authorization to the service (line 3):

    // GET: api/values  
    [HttpGet]  
    [Authorize(Policy = "ReadScope")]  
    public IEnumerable<ToDo> Get()  
    {  
        string owner = User.Identity.Name;  
        return TodoStore.Values.Where(x => x.Owner == owner);  
    }  

Is this (line 3) not required?

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,574 questions
{count} votes

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.