In the Microsoft docs written:
In a browser-based app, cookie authentication allows existing user credentials to automatically flow to SignalR connections. When using the browser client, no extra configuration is needed. If the user is logged in to an app, the SignalR connection automatically inherits this authentication.
Cookies are a browser-specific way to send access tokens, but non-browser clients can send them. When using the .NET Client, the Cookies property can be configured in the .WithUrl call to provide a cookie. However, using cookie authentication from the .NET client requires the app to provide an API to exchange authentication data for a cookie.
So but after a lot of searching, I couldn't find anything useful to pass the cookies. Nevertheless, I managed to do it in a certain way, but I'm not sure if it's the best or even a good way. Please help if there is a better way.
1- Inject the IHttpContextAccessor in razor page.
@inject IHttpContextAccessor HttpContextAccessor
2- Read all cookies from IHttpContextAccessor and add them to connection cookies.
protected override async Task OnInitializedAsync()
{
var uri = new UriBuilder(Navigation.Uri);
hubConnection = new HubConnectionBuilder()
.WithUrl(Navigation.ToAbsoluteUri("/chathub"), opti =>
{
if (HttpContextAccessor.HttpContext != null)
foreach (var c in HttpContextAccessor.HttpContext.Request.Cookies)
{
opti.Cookies.Add(new Cookie(c.Key, c.Value)
{
Domain = uri.Host, // Set the domain of the cookie
Path = uri.Path // Set the path of the cookie
});
}
})
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
var encodedMsg = $"{user}: {message}";
messages.Add(encodedMsg);
InvokeAsync(StateHasChanged);
});
await hubConnection.StartAsync();
}
3- Now you can decorate your hub with AuthorizeAttribute.
[Authorize]
public class ChatHub : Hub
{
public override Task OnConnectedAsync()
{
return base.OnConnectedAsync();
}
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
Passing cookies to the SignalR connection automatically from the Blazor-Server razor page