dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.43k stars 10.01k forks source link

SignalR - Getting user claims through dependency injection #53014

Open co-dax opened 10 months ago

co-dax commented 10 months ago

Is there an existing issue for this?

Describe the bug

How can I get current user claims outside of a Hub?

My usecase is a multy tenant application where EF Core DbContext is seeded with a TenantId value that in the case of a HTTP request is being extracted within DbContext constructor from current user claims by injecting IHttpContextAccessorinto the DbContext constructor and then finding the necessary user claim as follows IHttpContextAccessor.HttpContext.User.Claims.FirstOrDefault(x => x.Type == "tenantId").Value but I could not find a way of doing an analogous approach in the case of SignalR Hub method call, that is, I could not find a way of injecting current user claims via dependency injection in the case of a SignalR Hub method call in a similar way like it is possible in the conext of HTTP call (as I have described above). So the question is whether there is a way to access HubCallerContext or at least ClaimsPrincipal through a service outside of a Hub?

The only related info I could find is the following comment from @analogrelay (here is the link to it):

This is by design. There is no active HTTP request in your application when using Azure SignalR. If what you're trying to do is access claims on the user, those should have been copied over to the HubCallerContext.User property (accessible via the Context property on your Hub).

Expected Behavior

No response

Steps To Reproduce

No response

Exceptions (if any)

No response

.NET Version

No response

Anything else?

No response

seble-nigussie commented 6 months ago

I'm facing the same issue. @co-dax have you found a solution for this?

co-dax commented 6 months ago

@seble-nigussie you can accomplish this using hub filter.