Search code examples
asp.net-core-2.0asp.net-core-signalr

ASP.NET Core 2.0 Signalr pass data from authorization requirement to hub


I have an authorization requirement which makes sure the access token in the http header is valid:

class AccessTokenRequirement : AuthorizationHandler<AccessTokenRequirement>, IAuthorizationRequirement 
{
     protected async override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccessTokenRequirement requirement)
     {
         //...
     }
}

I am adding this requirement to the mvc pipeline in the startup.cs class as follows:

services.AddAuthorization(options =>
{
    options.AddPolicy("AccessToken", policy => policy.Requirements.Add(
       services.BuildServiceProvider().GetRequiredService<AccessTokenRequirement>()));
});

I then use this requirement on my signalr hubs like so:

[Authorize(Policy = "AccessToken")]
public class MyHub : Hub

Inside the authorization requirement I check the token and identify the user by hitting the database. My question is how can I access the user details INSIDE the hub methods? What is an elegant way to pass information from inside an authorization requirement to my hub methods? I have read into the Identity concept in asp.net but found it to be difficult to comprehend. Thanks in advance.


Solution

  • You have access to the ClaimsPrincipal inside your Hub via Context.User.

    Is that the information you want or is there something else you want access to in your Hub?