我创建了一个 Blazor 服务器应用程序,以开始学习 Blazor 和一些更新的技术。我遵循了 Microsoft 提供的集线器聊天教程。事情进展顺利。然后我添加了一些基本的 cookie 身份验证,事情仍然在进展中。然后,我按照 Carl Franklin 在 Blazor Train 上发布的有关将应用程序连接到 Azure AD B2C 的教程进行操作。除了应用程序的聊天中心部分之外,它可以工作。应用程序的所有其他部分都工作正常并显示用户的信息。
我几乎可以肯定"hubconnection"
失败是因为它没有获得访问令牌而没有进行身份验证。故障发生在await hubConnection.StartAsync();
与错误一致System.Text.Json.JsonReaderException: '<' is an invalid start of a value
。我非常确定 HTML 会返回 403 消息或类似的消息。
所以我想我在技术上有两个问题:
-
我怎样才能查看value
这导致了HubConnectionBuilder
出错?即使我设置了断点,我也永远看不到导致它阻塞的值是什么。
-
如何将访问令牌传递给 HubConnectionBuilder?
我发现了很多“方法”来做到这一点,但这些方法要么已经过时,要么无法工作:
使用已弃用的 AddAzureADB2CBearer https://stackoverflow.com/questions/61856216/how-to-use-azure-ad-b2c-with-xamarin-forms-and-signalr-core
将参数传递给我无法工作的应用程序 https://stackoverflow.com/questions/59538318/how-to-use-the-httpcontext-object-in-server-side-blazor-to-retrieve-information/59538319#59538319
适用于 Azure AD,不适用于 B2C https://github.com/javiercn/blazor-server-aad-sample
这是 Cookie 身份验证的工作原理:
hubConnection = new HubConnectionBuilder()
.WithUrl(
NavigationManager.ToAbsoluteUri("/chathub"),
config => config.UseDefaultCredentials = true)
.Build();
现在看来我需要传递一个基于以下的访问令牌这个关于 Auth 和 SignalR 的 Microsoft 页面 https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-5.0 but
hubConnection = new HubConnectionBuilder()
.WithUrl(
NavigationManager.ToAbsoluteUri("/chathub"), options =>
{
options.AccessTokenProvider = () => Task.FromResult(_myAccessToken);
})
.Build();
以下是我在 Startup 中所做的,以使 B2C 工作基于
//****Azure B2C****//
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAdB2C"));
services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy
options.FallbackPolicy = options.DefaultPolicy;
});
services.AddRazorPages();
services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();