dotnet / dotnet/aspnetcore

SignalR - Getting user claims through dependency injection

Open
#53,014 2 comments 0 reactions 0 assignees View on GitHub
area-signalr
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### 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 `IHttpContextAccessor `into 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](https://github.com/dotnet/aspnetcore/issues/12535#issuecomment-514900103)):

> 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_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.