1

I am facing an issue that /nagotiate request fails with 401(Unauthorized).

Server

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR(options => {
                options.EnableDetailedErrors = true;
            })
            .AddAzureSignalR(options =>
            {
                options.InitialHubServerConnectionCount = 1;
                options.ConnectionString = "xxxx"

            });
}

protected virtual void ConfigureAuthentication(IServiceCollection services)
{
    services
        .AddAuthentication(options =>
        {
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.Authority = $"{AzureB2CConfig.Instance}/{AzureB2CConfig.Domain}/{AzureB2CConfig.SignUpSignInPolicyId}/v2.0/";
            options.Audience = AzureB2CConfig.Audience;

            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    var authToken = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");

                    var path = context.HttpContext.Request.Path;
                    if (!string.IsNullOrEmpty(authToken) &&
                        (path.StartsWithSegments("/myhubs")))
                    {
                        context.Token = authToken;
                    }

                    return Task.CompletedTask;
                }
            };

            options.TokenValidationParameters =
                new TokenValidationParameters
                {
                    LifetimeValidator = (before, expires, token, param) =>
                    {
                        return expires > DateTime.UtcNow;
                    },
                    ValidateAudience = false,
                    ValidateIssuer = false,
                    ValidateActor = false,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = false
                };
        });

    services.AddAuthorization(options =>
    {
        options.AddPolicy("AllowedUser", policy =>
        {
            policy.Requirements.Add(new AllowedUserRequirement());
        });
    });

}

public void Configure(IApplicationBuilder app)
{

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseFileServer();
    app.UseEndpoints(routes =>
    {
        routes.MapHub<MyHub>($"/myhubs");
        
    });

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Client

 var connection = new HubConnectionBuilder()
  .WithUrl(SignalRServerUrl, options =>
  {
      options.AccessTokenProvider = authenticationService.GetAccessToken; // returns valid access token
  })
  .WithAutomaticReconnect()
  .Build();

 await Policy
     .Handle<Exception>()
     .WaitAndRetryAsync(1, x => TimeSpan.FromMilliseconds(500))
     .ExecuteAsync(() => _connection.StartAsync()); // causes 401 Unauthorized

I have tried many things but none of them helped.

I have read a lots of articles and here is example. this, this, this, this, this, this,this, this and have spend few days for finding the solution but could not..

Are there any missing configuration?

FrameWork: .Net6

Updated at 20th Oct 2022

I Added services.AddAuthorization() parts and Authentication is now success between the app and the server. But app connects to Azure SignalR. This Azure SignalR authentication is failing. 401

Takeo Nishioka
  • 369
  • 2
  • 11

0 Answers0