👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
Streaming and Authentication and Authorization in SignalR

Streaming and Authentication and Authorization in SignalR

Author - Abdul Rahman (Bhai)

SignalR

8 Articles

Improve

Table of Contents

  1. What we gonna do?
  2. Why we gonna do?
  3. How we gonna do?
  4. Summary

What we gonna do?

In this article, let's learn about Streaming and Authentication and Authorization in SignalR.

Note: If you have not done so already, I recommend you read the article on Exception Handling and Logging in SignalR.

In our previous article, we learnt about Exception Handling and Logging and how to configure them. Today in this article, lets learn about how to do streaming and touch base on authentication and authorization in SignalR.

Why we gonna do?

Not all data fits neatly into a single hub message. When dealing with sequences of data that arrive over time — such as live sensor readings, progress updates, or real-time scores — streaming is the right tool. Without it, developers have to either poll repeatedly or buffer all data before sending, neither of which is efficient.

Authentication and Authorization are equally important. SignalR hubs maintain persistent connections, and without proper access control, any connected client could receive notifications meant for authenticated users only.

Understanding when to use streaming and how to apply the [Authorize] attribute on hubs, along with JWT token configuration, ensures your real-time application is both efficient and secure.

How we gonna do?

Streaming

Streaming with SignalR is pretty specialized. If we're talking about using WebSockets for connections, the messages flying back and forth don't weigh much in terms of overhead. Since the connection's already set up, the biggest chunk of overhead is likely in serializing and deserializing, which happens pretty quickly. So if you're passing things like real time data, the regular SignalR transport should do the trick just fine.

But streaming isn't the best fit for everything, especially not for binary data like audio and video. SignalR uses a JSON-based transport, even if it's using MessagePack, which means JSON gets turned into binary. So, not the smoothest ride for raw binary data like audio and video.


// Server
public class AsyncEnumerableHub : Hub
{
    public async IAsyncEnumerable<int> Counter(
            CountInfo countInfo,
            [EnumeratorCancellation]
            CancellationToken cancellationToken)
    {
            for (var i = 0; i < countInfo.CountUntil; i++)
            {
                // Check the cancellation token regularly so that the server will stop
                // producing items if the client disconnects.
                cancellationToken.ThrowIfCancellationRequested();

                yield return i;

                // Use the cancellationToken in other APIs that accept cancellation
                // tokens so the cancellation can flow down to them.
                await Task.Delay(countInfo.DelayMilliSeconds, cancellationToken);
            }
    }
}

// Client
var cts = new CancellationTokenSource();
var stream = connection.StreamAsync<int>("Counter", new CountInfo { CountUntil = 10, DelayMilliSeconds = 500 }, cts.Token);
await foreach (var count in stream)
{
   Console.WriteLine(count);
}
            

Authentication & Authorization

The cool thing is that the SignalR hub can make use of everything that's in ASP.NET Core already. We can just put the Authorize attribute above ILoveDotNetHub and now users that don't have a valid credentials can't access it. SignalR supports both JWT and Cookie authentication. Here is the example for JWT authentication.


//Server
[Authorize]
public class ILoveDotNetHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        // Accessing the claims
        var claims = Context.User.Claims;
    }
}

//Client
new HubConnectionBuilder()
     .WithUrl($"{Configuration.GetValue<string>("ApiBaseAddress")}notifications",
     options =>
     {
         options.AccessTokenProvider = async () =>
         {
             var accessTokenResult = await TokenProvider.RequestAccessToken();
             accessTokenResult.TryGetToken(out var token);
             return token!.Value;
         };
     })
     .Build();
            

Authorization doesn't work any differently with SignalR than it does with any other ASP.NET Core application. You can use Context.User.Claims and get the claims and work on them.

Summary

In this article, we learnt about Streaming and Authentication and Authorization in SignalR. In the next article, we will learn about Design Considerations and Deployment & Scaling in SignalR.

👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
  • Signalr
  • Streaming
  • Authentication
  • Authorization