0
votes

I have a problem. I have in my API JWT Bearer authentication. I try to use signalr hub with authentication but it doesnt work for me. I have something like this:

    .AddJwtBearer(conf =>
                {
                    conf.RequireHttpsMetadata = false;
                    conf.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                    conf.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = context =>
                        {
            //THIS DONT WORK - empty string
                            //var accessToken = context.Request.Query["access_token"];
                            var accessToken2 = context.Request.Headers["Authorization"];
                            // If the request is for our hub...
                            var path = context.HttpContext.Request.Path;
                            if (!string.IsNullOrEmpty(accessToken2) &&       
                            (path.StartsWithSegments("/DebateHub")))
                            {
                                // Read the token out of the query string
                                context.Token = accessToken2;     
                            }
                           // return Task.CompletedTask;
                           return Task.FromResult<object>(null);
                        }
                    };
                });

Register hub:

 app.UseEndpoints(endpoints =>
        {
            endpoints.MapAreaControllerRoute(
                name: "AreaAdmin",
                areaName: "Admin",
                pattern: "api/admin/{controller}/{action}");

            endpoints.MapAreaControllerRoute(
                name: "AreaMobile",
                areaName: "Mobile",
                pattern: "api/mobile/{controller}/{action}");

            endpoints.MapControllers();
            endpoints.MapHub<DebateHub>("/DebateHub");
            endpoints.MapHub<OnlineCountHub>("/onlinecount");
        });

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class DebateHub : Microsoft.AspNetCore.SignalR.Hub
{      
    public override Task OnConnectedAsync()
    {
     
        string name = Context.User.Identity.Name;      
       
        Groups.AddToGroupAsync(Context.ConnectionId, name);
       
        return base.OnConnectedAsync();
    }

Client example:

        var uri = "https://localhost:44275/DebateHub";         
        
        var connection = new HubConnectionBuilder()

            .WithUrl(uri,options =>
            {                   
                options.AccessTokenProvider = () => Task.FromResult("some_token");
                
            })
            .Build(); 
        connection.StartAsync().Wait();

It doesn't work. I still have unauthorized when I try to connect to my DebateHub. All other controllers work with my authentication ok. What I'm doing wrong?

1

1 Answers

0
votes

I'm not sure but I think that you should use cookies to authorize to hub.

Look here