I Use SignalR for RealTime Communication in my application But in OnConnectAsync method the Context.user always null

Soundhar M 50 Reputation points
2024-08-25T04:22:32.2866667+00:00

“I use SignalR Core, not Azure SignalR service, for real-time communication in my application. However, in the OnConnectAsync method, the Context.User is always null. I use Python for the login process where the token is created, and I use .NET for SignalR.”

Is there anything else you need help with?

Azure SignalR Service
Azure SignalR Service
An Azure service that is used for adding real-time communications to web applications.
147 questions
0 comments No comments
{count} votes

Accepted answer
  1. brtrach-MSFT 16,586 Reputation points Microsoft Employee
    2024-08-27T03:26:12.4833333+00:00

    @Soundhar M hen using SignalR Core with Python for the login process, you may need to configure your application to use a custom authentication provider to pass the authentication token to SignalR.

    One way to do this is to implement a custom authentication provider in your SignalR Core application that can read the authentication token from the request headers and set the user identity for the connection. Here is an example of how you can do this:

    public class CustomAuthenticationProvider : IUserIdProvider
    {
        public string GetUserId(HubConnectionContext connection)
        {
            // Get the authentication token from the request headers
            string token = connection.GetHttpContext().Request.Headers["Authorization"];
    
            // Validate the token and extract the user identity
            // ...
    
            // Set the user identity for the connection
            return userId;
        }
    }
    
    public class MyHub : Hub
    {
        public override Task OnConnectedAsync()
        {
            // Set the user identity for the connection
            Context.User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, Context.User.Identity.Name) }));
    
            return base.OnConnectedAsync();
        }
    }
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.Authentication
    
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.