Here I have simple private chat application in blazor server signalR where user logins, addfriend and chat with that friend.
For login I have used AspNetCore.Identity
.
Now, the problem is that the application works perfectly fine in local machine but as I run application in ngrok()
there is an error saying
Error: System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
ngrok is a cross-platform application that enables developers to expose a local development server to the Internet.
The software makes locally-hosted web server appear to be hosted on a subdomain of ngrok.com, meaning that no public IP or domain name on the local machine is needed
Below is what have done to authenticate user to signlar hub
In 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>
In 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();
}
}
CookiesProvider.cs
public class CookiesProvider
{
public string Cookie { get; set; }
}
In webchat.razor
@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();
}
}
In hub
[Authorize()]
public class ChatHub : Hub
{
}