LESSON 10 OF 14

10. Authorization, User Scope, and Secure Hub Methods

Learn how to secure SignalR hubs with roles, policies, and resource ownership, while testing group access, UserIdentifier usage, and IDOR risks.

35 dk 51

Introduction

In the previous lesson, we secured SignalR connections with JWT authentication. Authentication establishes who the user is; authorization determines what that user is allowed to do. In this lesson, we will apply authorization at the hub, method, group, and resource levels.

Our example is a project management application. Users can join only the project groups to which they belong, receive project messages, and update tasks in projects they are allowed to access. Managers can perform additional operations, such as archiving a project.

The central security rule is simple: values supplied by the client, such as userId, role, projectId, or a group name, must not be trusted for authorization. Decisions should be based on validated JWT claims and resource data loaded by the server.

Separating authorization levels

SignalR applications commonly use three authorization levels:

  • Hub-level authorization: Only authenticated users can establish a connection to the hub.
  • Method-level authorization: A particular hub method is limited to users who satisfy a role or policy.
  • Resource-level authorization: The server checks whether a user may operate on a specific project, document, or task.

The first two levels can usually be implemented with [Authorize]. Resource-owner checks require the application to load the resource first and then call IAuthorizationService. An attribute alone cannot determine ownership of a resource that has not yet been loaded.

Hub- and method-level policies

Start by defining policies. The role claim in the JWT must match the claim mapping used by your application. The following example assumes standard role claim mapping.

using Microsoft.AspNetCore.Authorization;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication()
    .AddJwtBearer(options =>
    {
        options.Authority = "https://identity.example.com";
        options.Audience = "realtime-api";
    });

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("ProjectMember", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("permission", "project:read");
    });

    options.AddPolicy("ProjectManager", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireRole("ProjectManager", "Admin");
    });
});

builder.Services.AddSignalR();

Authentication and authorization middleware must also be registered in the correct order:

var app = builder.Build();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapHub<ProjectHub>("/hubs/projects");
app.Run();

Use a class-level attribute to protect the entire hub and a method-level attribute for especially sensitive operations.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;

[Authorize]
public class ProjectHub : Hub
{
    [Authorize(Policy = "ProjectMember")]
    public Task GetProjectSnapshot(string projectId)
    {
        return Task.CompletedTask;
    }

    [Authorize(Policy = "ProjectManager")]
    public Task ArchiveProject(string projectId)
    {
        return Task.CompletedTask;
    }
}

When a client invokes a method without satisfying its policy, the invocation fails. The client should catch the error, display an appropriate message, and avoid exposing sensitive implementation details.

Claims, UserIdentifier, and private messages

Context.User contains the authenticated ClaimsPrincipal for the connection. SignalR can send a message to all connections associated with a user through Clients.User(...). By default, SignalR uses ClaimTypes.NameIdentifier as the user identifier.

If your identity provider uses another claim, implement a custom IUserIdProvider. The selected value must be unique and stable for every user. Using an email address as the user identifier can be problematic because addresses may change and normalization rules may differ. A stable subject or provider-issued user ID is usually a better choice.

using Microsoft.AspNetCore.SignalR;

public sealed class SubjectUserIdProvider : IUserIdProvider
{
    public string? GetUserId(HubConnectionContext connection)
    {
        return connection.User?.FindFirst("sub")?.Value;
    }
}

builder.Services.AddSingleton<IUserIdProvider, SubjectUserIdProvider>();

Inside the hub, use the authenticated identity rather than a client-supplied user ID:

public async Task SendPrivateNotice(string text)
{
    var userId = Context.UserIdentifier;

    if (string.IsNullOrWhiteSpace(userId))
        throw new HubException("The user identifier is missing.");

    await Clients.User(userId).SendAsync("NoticeReceived", new
    {
        Text = text,
        SentAt = DateTimeOffset.UtcNow
    });
}

Even a user-specific channel is not automatically safe. If the method allows a user to trigger arbitrary notifications or access sensitive data, it still needs a policy or business-rule check.

Secure group membership

Groups are not an access-control mechanism. Membership is maintained in memory, may need to be recreated after reconnection, and must be reviewed when a user's permissions are revoked. Validate project membership before adding the connection to a group.

[Authorize(Policy = "ProjectMember")]
public async Task JoinProject(string projectId)
{
    var userId = Context.UserIdentifier;

    if (string.IsNullOrWhiteSpace(userId))
        throw new HubException("The user is not authenticated.");

    var isMember = await projectAccessService
        .IsMemberAsync(projectId, userId, Context.ConnectionAborted);

    if (!isMember)
        throw new HubException("You are not authorized for this project.");

    var groupName = $"project:{projectId}";
    await Groups.AddToGroupAsync(
        Context.ConnectionId,
        groupName,
        Context.ConnectionAborted);
}

Generate group names on the server instead of using an arbitrary client-provided value. Also validate the project ID format and reject invalid or excessively long values.

Resource-owner authorization

A role claim alone may not tell you whether a user can update a particular task. Ownership, project membership, or organization-level permissions are usually stored in the database. Resource-based authorization is appropriate for these cases.

public sealed record TaskItem(
    string Id,
    string ProjectId,
    string OwnerId,
    string Title);

public sealed class TaskOwnerRequirement : IAuthorizationRequirement;

public sealed class TaskOwnerHandler
    : AuthorizationHandler<TaskOwnerRequirement, TaskItem>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        TaskOwnerRequirement requirement,
        TaskItem resource)
    {
        var userId = context.User.FindFirst("sub")?.Value;

        if (userId == resource.OwnerId ||
            context.User.IsInRole("Admin"))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

Register the handler and policy:

builder.Services.AddSingleton<IAuthorizationHandler, TaskOwnerHandler>();

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("TaskOwner", policy =>
        policy.Requirements.Add(new TaskOwnerRequirement()));
});

In the hub method, load the resource first and then evaluate the policy:

[Authorize]
public class TaskHub : Hub
{
    private readonly ITaskRepository tasks;
    private readonly IAuthorizationService authorization;

    public TaskHub(
        ITaskRepository tasks,
        IAuthorizationService authorization)
    {
        this.tasks = tasks;
        this.authorization = authorization;
    }

    public async Task UpdateTitle(string taskId, string title)
    {
        var task = await tasks.FindAsync(taskId, Context.ConnectionAborted);

        if (task is null)
            throw new HubException("The task was not found.");

        var result = await authorization.AuthorizeAsync(
            Context.User!, task, "TaskOwner");

        if (!result.Succeeded)
            throw new HubException("You cannot modify this task.");

        await tasks.UpdateTitleAsync(taskId, title.Trim());
        await Clients.Group($"project:{task.ProjectId}")
            .SendAsync("TaskUpdated", taskId, title);
    }
}

The client cannot gain access by supplying another ownerId. The decision is based on the actual resource loaded from the database.

Common mistakes

  • Only hiding the user interface: Hiding a button is not authorization. The hub method must reject unauthorized calls on the server.
  • Trusting client roles: A client-supplied role or isAdmin property must never determine authorization.
  • Omitting [Authorize] from the hub: Without authorization metadata, an anonymous connection may be able to invoke hub methods.
  • Using an attribute for ownership checks: Dynamic ownership checks require the resource to be loaded and authorization to be evaluated imperatively.
  • Treating groups as security boundaries: Validate membership before joining and review existing connections when permissions are revoked.
  • Using a mutable claim as the user ID: If UserIdentifier changes, private messages may be lost or routed incorrectly.
  • Ignoring permission changes: Long-lived connections may retain claims from connection time. For sensitive methods, consider current database checks and a strategy for closing affected connections.

Practice exercise

Create a DocumentHub. Users may join only document groups for documents they can access. The owner can change the title, users with the Editor role can update content, and only users with the Admin role can delete a document.

  1. Add [Authorize] to the hub.
  2. Define Editor and Admin policies.
  3. In JoinDocument, obtain the authenticated user ID through Context.UserIdentifier.
  4. Load the document and evaluate ownership through IAuthorizationService.
  5. Test calls with a different userId, a forged role, and another documentId.
  6. Verify that unauthorized calls fail and successful calls publish notifications only to the appropriate document group.

Conclusion

A secure SignalR application is more than an application that validates JWTs. Authorization decisions should exist at the hub, method, group, and resource levels. Context.User and trusted claims define the authenticated user scope, Context.UserIdentifier provides the target for user-specific messages, and IAuthorizationService helps evaluate ownership of database-backed resources.

In the next lesson, we will connect this security model to connection lifetime, token refresh, and automatic reconnection scenarios.

Sources