How to Do Authentication with SignalR?


How to Do Authentication with SignalR?

Authentication is one of the most critical steps in real-time web applications. Especially in projects built with SignalR, user authentication needs to be designed correctly to ensure the connection is secure. In this article, we will discuss in detail how to do authentication with SignalR and what are the most efficient and reliable methods.

SignalR Authentication Architecture

SignalR establishes a constantly open, bidirectional communication line between the client and server. As in standard Http APIs, the authentication process with SignalR is also carried out in the middleware layer. SignalR can easily integrate with both Cookie-based and token-based authentication methods such as JWT Bearer.

JWT Bearer Authentication Example in ASP.NET Core SignalR

Below you can find one of the simplest examples of using authentication with JWT in a SignalR hub. In this method, the token sent from the client is validated in the server, and each connection is securely processed in the user context.


// Authentication setup in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "yourdomain.com",
            ValidAudience = "yourdomain.com",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"))
        };
        options.Events = new JwtBearerEvents
        {
            OnMessageReceived = context =>
            {
                // Get the access_token sent with SignalR
                var accessToken = context.Request.Query["access_token"];

                // If it's the signalr path, use the token
                var path = context.HttpContext.Request.Path;
                if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs/chat"))
                {
                    context.Token = accessToken;
                }
                return Task.CompletedTask;
            }
        };
    });

    services.AddSignalR();
}

On the client side, you need to send the access_token parameter when connecting:


const connection = new signalR.HubConnectionBuilder()
    .withUrl("/hubs/chat", {
        accessTokenFactory: () => token
    })
    .build();

Things to Consider in SignalR Authentication

When using authentication with SignalR, TLS support (HTTPS) must be mandatory for connection security. Also, details such as token expiry received from the user, role/permission control, and whether anonymous users will be allowed should be thoroughly considered. Below you can see a control example structured for authentication in a SignalR hub:


public class ChatHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        // User authentication control
        if (!Context.User.Identity.IsAuthenticated)
        {
            Context.Abort();
        }
        await base.OnConnectedAsync();
    }

    public Task SendMessage(string message)
    {
        var userName = Context.User.Identity.Name;
        return Clients.All.SendAsync("ReceiveMessage", userName, message);
    }
}

Conclusion

Doing authentication with SignalR is essential to ensure security in modern web applications. With JWT or cookie-based authentication methods, it is possible to increase both security and performance in real-time communication with SignalR. Especially by applying authentication with SignalR, you can easily ensure that sensitive data is shared only among authenticated and authorized users.