在这里,我在 blazor 服务器 signalR 中有一个简单的私人聊天应用程序,用户可以在其中登录、添加好友并与该好友聊天。
对于登录,我使用了 AspNetCore.Identity
。
现在,问题是该应用程序在本地机器上运行得非常好,但是当我在 ngrok()
中运行应用程序时,出现错误说
Error: System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
ngrok 是一个使开发人员能够将本地开发服务器公开到 Internet 的跨平台应用程序。
该软件使本地托管的 Web 服务器看起来托管在 ngrok.com 的子域上,这意味着不需要本地计算机上的公共 IP 或域名
以下是向信号集线器验证用户所做的工作
在 Host.cshtml 中
@{
var cookie = HttpContext.Request.Cookies[".AspNetCore.Identity.Application"];
}
<body>
@* Pass the captured Cookie to the App component as a paramter*@
<component type="typeof(App)" render-mode="Server" param-Cookie="cookie" />
</body>
在 App.razor 中
@inject CookiesProvider CookiesProvider
@* code omitted here... *@
@code{
[Parameter]
public string Cookie { get; set; }
protected override Task OnInitializedAsync()
{
// Pass the Cookie parameter to the CookiesProvider service
// which is to be injected into the Chat component, and then
// passed to the Hub via the hub connection builder
CookiesProvider.Cookie = Cookie;
return base.OnInitializedAsync();
}
}
public class CookiesProvider
{
public string Cookie { get; set; }
}
@attribute [Authorize]
@* code omitted here... *@
@code{
protected override async Task OnInitializedAsync()
{
var container = new CookieContainer();
var cookie = new Cookie()
{
Name = ".AspNetCore.Identity.Application",
Domain = "localhost",
Value = CookiesProvider.Cookie
};
container.Add(cookie);
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/chathub"), options =>
{
// Pass the security cookie to the Hub.
options.Cookies = container;
}).Build();
await hubConnection.StartAsync();
}
}
[Authorize()]
public class ChatHub : Hub
{
}