In ASP.NET Core SignalR, what does [Authorize] on a hub class check compared with [Authorize] on a hub method, and when is each evaluated?
answer
- class attributes become endpoint metadata
- negotiate refused with 401 or 403
- method attribute checked on every invocation
- "Failed to invoke ... because user is unauthorized"
- Context.User cached for the connection
basics
~20 s[Authorize] on the hub class becomes endpoint metadata on the hub's negotiate and connection endpoints, so unauthorized clients are refused before a connection exists. [Authorize] on a method is checked on every invocation against Context.User, the principal captured when the connection started.
solid answer
~50 s`MapHub<T>` copies every attribute on the hub class onto the hub's endpoints, `/negotiate` and the connection endpoint, so `[Authorize]` there is enforced by the authorization middleware: an anonymous negotiate gets `401`, an authenticated user failing the policy gets `403`, and the client's `start()` fails. `MapHub<T>(...).RequireAuthorization("policy")` does the same from Program.cs. `[Authorize(Policy = ...)]` or `Roles` on a hub method is checked by the hub dispatcher each time that method is invoked; a refused call gets the error "Failed to invoke 'X' because user is unauthorized" and the connection stays open. Policy handlers receive a `HubInvocationContext` as the resource. Both checks use the principal SignalR captured when the connection was established, so a removed role or revoked token does not take effect until the connection closes, unless `CloseOnAuthenticationExpiration` closes it at token expiry. In ASP.NET Core 10, cookie authentication answers every request to a hub endpoint with `401` or `403` instead of a login redirect.
code
csharp · 16 lines[Authorize]
public class QuotesHub : Hub
{
public Task Subscribe(string symbol) =>
Groups.AddToGroupAsync(Context.ConnectionId, symbol);
[Authorize(Roles = "Moderator")]
public Task CloseMarket(string symbol) =>
Clients.Group(symbol).SendAsync("MarketClosed", symbol);
}
// Program.cs
app.MapHub<QuotesHub>("/hubs/quotes", options =>
{
options.CloseOnAuthenticationExpiration = true;
});go deeper
Recall that [Authorize] works on a hub class to require a signed-in user and on a hub method to restrict that one call.
Explain that class attributes become endpoint metadata on negotiate and the connection, while method attributes are checked per invocation by the hub dispatcher with a HubInvocationContext resource.
Point out that both checks use the principal cached at connect, what that means for revoked roles and expired tokens, and when CloseOnAuthenticationExpiration is worth its missed messages.
Decide how fast permission changes must reach live connections, and whether forced reconnects, short tokens or explicit connection termination fit the product's risk.
## Two places, two moments | Attribute placed on | Enforced by | When | Failure looks like | |---|---|---|---| | Hub class | authorization middleware, via endpoint metadata | on `/negotiate` and on each transport request | `401` or `403`; `start()` rejects | | Hub method | the hub dispatcher | every invocation of that method | an invocation error; the connection stays open | | `MapHub<T>(...).RequireAuthorization(...)` | authorization middleware | same as a class attribute | same as a class attribute | ## Hub-level: endpoint authorization `MapHub<QuotesHub>("/hubs/quotes")` maps two endpoints: `/hubs/quotes/negotiate` and `/hubs/quotes` itself, which carries the WebSocket, Server-Sent Events and long-polling traffic. It adds every attribute on the hub class, `[Authorize]` and `[EnableCors]` included, to the metadata of both. From then on the normal endpoint rules apply: - an anonymous request is challenged, so a JWT bearer scheme returns **401**; - an authenticated user who fails the policy is forbidden, **403**; - the JavaScript client's `start()` rejects with the HTTP error, and no hub code runs. `RequireAuthorization()` on the `MapHub` result is equivalent and keeps the policy next to the route. ## Method-level: per invocation Attributes on individual hub methods are not endpoint metadata. The hub dispatcher reads them and calls the authorization service each time a client invokes the method: 1. The client sends an invocation message for `CloseMarket`. 2. The dispatcher evaluates the method's policies against `Context.User`, passing a `HubInvocationContext` (hub, method, arguments) as the resource, so a handler can inspect the call. 3. On failure it logs "Failed to invoke 'CloseMarket' because user is unauthorized." and sends the caller an invocation error with that text; the method never runs. 4. The connection stays open and other methods still work. This is how one hub serves readers and moderators: `[Authorize]` on the class, `[Authorize(Roles = "Moderator")]` on the few methods that change state. ## The cached principal SignalR captures the authenticated user when the connection is established and keeps it for the connection's lifetime. It does not re-validate it: - removing a role from a user does not stop their open connection calling role-protected methods; - revoking or expiring a bearer token does not close an open WebSocket; - with long polling, each request is authenticated again by the middleware, but hub authorization still uses the cached principal. `HttpConnectionDispatcherOptions.CloseOnAuthenticationExpiration`, `false` by default and set in the `MapHub` options, closes a connection once the authentication's expiry passes. The client must reconnect and re-authenticate, and it misses messages sent while it was closed. For immediate revocation, close affected connections yourself. ## Cookie authentication in ASP.NET Core 10 Cookie authentication has long answered `401` instead of redirecting when a request carries `X-Requested-With: XMLHttpRequest`, and the SignalR clients send that header on their HTTP requests. Requests that cannot carry it, such as a browser's WebSocket upgrade or `EventSource` request, used to get a `302` to the login page. In ASP.NET Core 10 the hub's endpoints carry metadata that disables cookie login redirects, so **every** request to them gets **401** or **403**. The app-wide switch `Microsoft.AspNetCore.Authentication.Cookies.IgnoreRedirectMetadata` restores the old behaviour. JWT bearer authentication never redirected, so nothing changes there.
- What does a policy handler receive as the resource when it runs for a SignalR hub method?A `HubInvocationContext`. It exposes the hub instance, the `HubCallerContext`, the method being invoked and its arguments, so a handler can, for example, allow `CloseMarket` only for symbols the user moderates. Writing the requirement and handler themselves is ordinary ASP.NET Core authorization.
- A user's Moderator role is removed while their SignalR connection is open. When do they lose access to CloseMarket?Only when the connection closes and they reconnect with a principal that lacks the role. Hub method authorization runs on every call, but against the `Context.User` captured at connect time, which SignalR does not refresh. To revoke immediately, close that user's connections yourself.
- [Authorize] on a hub method rejects the connection when the client connects.
- A failed hub method authorization closes the client's connection.
- SignalR re-validates the user's token before every hub method call.
- In ASP.NET Core 10, cookie authentication still redirects an anonymous negotiate to the login page.
- [Authorize] on the hub class is ignored because hubs are not controllers.
Assumes ASP.NET Core 10, where SignalR hub endpoints carry metadata that makes cookie authentication answer every hub request with 401 or 403 instead of a login redirect.