Microsoft.Identity.Web 和 ASP.NET Core SignalR JWT 身份验证

Jes*_*nds 5 azure signalr asp.net-core

我正在使用 ASP.NET Core 制作一个 Web 应用程序,该应用程序还使用 SignalR Core 来提供实时功能。我使用 Azure AD B2C 进行用户管理。我已成功使用Microsoft.Identity.Web( https://github.com/AzureAD/microsoft-identity-web ) 使用 Azure AD B2C 生成的令牌来保护我的 API 终结点。

我想对我的 SignalR Core 集线器做同样的事情。该文档读取将适当的注释添加到您的集线器/方法中,我已经这样做了。SignalR 的客户端库将访问令牌添加为查询参数,必须在 ASP.NET Core 应用程序的配置中手动提取该参数并将其添加到上下文中,如下所示。

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.Events = new JwtBearerEvents
        {
            OnMessageReceived = context =>
            {
                var accessToken = context.Request.Query["access_token"];

                // If the request is for our hub...
                var path = context.HttpContext.Request.Path;
                if (!string.IsNullOrEmpty(accessToken) &&
                    (path.StartsWithSegments("/hubs/chat")))
                {
                    // Read the token out of the query string
                    context.Token = accessToken;
                }
                return Task.CompletedTask;
            }
        };
    });
Run Code Online (Sandbox Code Playgroud)

Microsoft.Identity.Web但是,这似乎与此处提供的配置不兼容:

        services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAdB2C"));
Run Code Online (Sandbox Code Playgroud)

我怎样才能让 SignalR 与 一起工作Microsoft.Identity.Web

小智 9

应该这样做:

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(configuration);

services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
    Func<MessageReceivedContext, Task> existingOnMessageReceivedHandler = options.Events.OnMessageReceived;
    options.Events.OnMessageReceived = async context =>
    {
      await existingOnMessageReceivedHandler(context);

      StringValues accessToken = context.Request.Query["access_token"];
      PathString path = context.HttpContext.Request.Path;

      // If the request is for our hub...
      if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
      {
        // Read the token out of the query string
        context.Token = accessToken;
      }
    };
});
Run Code Online (Sandbox Code Playgroud)

您可以通过这种方式配置 JwtBearerOptions 对象,而不是添加 JwtBearer。

改编自本文档:https://github.com/AzureAD/microsoft-identity-web/wiki/customization

  • 可能不理想,但它完美地完成了任务,应该被接受 (2认同)

小智 0

您可以使用Visual Studio设置SignalR连接,然后只需在startup.cs中添加这一行(VS可能会自动添加它)

services.AddSignalR().AddAzureSignalR();
Run Code Online (Sandbox Code Playgroud)

此开发示例已设置 SignalR,只是缺少连接字符串,但可能会让您了解要做什么。大部分工作都是用 VS 自动完成的。如果您在设置时遇到问题,请在存储库中提出问题。谢谢。