How to get the current user outside the controller in the .NET Core Web API

I am trying to get the current user from a context outside the controller in my web API. I use OpenIddict to authenticate users, so authorization is done using tokens.

I registered the HttpContextAcessor as singleton in my Startup.cs:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 

After that, I insert the HttpContexrAcessor into my hub, for example:

 public class NotificationHub : Hub { private IHttpContextAccessor _contextAccessor; private HttpContext _context { get { return _contextAccessor.HttpContext; } } public NotificationHub(IHttpContextAccessor contextAccessor) { _contextAccessor = contextAccessor; } public async Task JoinGroup() { Groups.Add(Context.ConnectionId, $"notification_{_context.User.Identity.Name}"); } public void Send(JsonResult notification) { Clients.Client(Context.ConnectionId).sendNotification(notification); } } 

The problem is that _context.User.Identity.Name is always null.

Is there any way to do this?

+6
source share
4 answers
0
source

Try removing this line from your launch:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

I believe that the structure is already registering this for you.

-one
source

I had the same problem. For me, the decision was expected to finish at the request. I published a team and did not wait for the result. For instance.

 PostSomething() { Task.Run(() => PostCommandAndDontWait()); } 

Now my httpContext user did not have the claims I was expecting. When I was waiting for the task to finish (deleting Task.Run, .Wait (). Result (), etc. I had a user with exceptions.

-one
source

Try the following:

 HttpContext.Current.User.Identity.Name 
-3
source

Source: https://habr.com/ru/post/1014422/


All Articles