0
votes

I authenticated to Signalr with Bearer token and signalr said Authentication was successful.

Authenticated image

But Signalr Hub Context.Identity.User.Name is null after authentication.

SignalR Hub

How can i access to authenticated user information in SignalR Hub for connectionid and user mapping.

My Startup.cs code for authentication.

 services.AddAuthentication(options =>
                    {
                        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                    {
                        options.Authority = "https://security.minima.local";
                        options.Audience = "blazor_web_app_api";
                        options.RequireHttpsMetadata = false;
    
                        options.TokenValidationParameters = new
                            TokenValidationParameters()
                            {
                                ValidateAudience = false
                            };
                        options.Events = new JwtBearerEvents
                        {
                            OnMessageReceived = context =>
                            {
                                var accessToken = context.Request.Query["access_token"];
                                var path = context.HttpContext.Request.Path;
                                if (!string.IsNullOrEmpty(accessToken) &&
                                    (path.StartsWithSegments("/notification")))
                                {
                                    context.Token = accessToken;
                                }
    
                                return Task.CompletedTask;
                            }
                        };
                    })
                    .AddIdentityServerJwt();
1
Do you know that your token contains a Name claim? Also, by default, SignalR uses the NameIdentifier claim for users, but you can customize that docs.microsoft.com/aspnet/core/signalr/…Brennan
In fact all claims are null (email etc) , but only NameIdentifier is not null. how can i take other claims with NameIdentifier?Emre Karahan

1 Answers

0
votes

You need to tell the TokenValidator which claim is the name and role claim and you do that by setting:

.AddMyJwtBearer(opt =>
    {
        ...
        opt.TokenValidationParameters.RoleClaimType = "roles";
        opt.TokenValidationParameters.NameClaimType = "name";