具有承载身份验证的 Azure SignalR 服务

标签 azure asp.net-core oauth signalr azure-signalr

我们正在尝试扩展我们的日历应用程序,该应用程序使用 SignalR 根据用户的 OrganizationId 向客户端推送更新。以前,SignalR 内容托管在单个应用程序服务器中,但为了使其能够跨多个服务器工作,我们选择使用 Azure SignalR 服务。

但是,当应用程序使用 Azure 解决方案时,自动权限就会中断。

Startup.cs 中设置身份验证,以便在处理 Hub 端点时在 url/查询字符串中查找 token :

//From: Startup.cs (abridged)
public IServiceProvider ConfigureServices(IServiceCollection services)
    var authenticationBuilder = services.AddAuthentication(options => {
            options.DefaultAuthenticateScheme = OAuthValidationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OAuthValidationDefaults.AuthenticationScheme;
        });
        
    authenticationBuilder
        .AddOAuthValidation(options => {
            options.Events.OnRetrieveToken = async context => {
                // Based on https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.0
                var accessToken = context.HttpContext.Request.Query["access_token"];

                var path = context.HttpContext.Request.Path;
                if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/signalr/calendar")) {
                    context.Token = accessToken;
                }
                return;
            };
        })
        .AddOpenIdConnectServer(options => {
            options.TokenEndpointPath = "/token";
            options.ProviderType = typeof(ApplicationOAuthProvider);
            /*...*/
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime applicationLifetime) {
        app.UseAuthentication();
}

使用 Azure SignalR 服务时,根本不会命中 OnRetrieveToken 事件代码,这是有道理的,因为请求不再定向到应用服务,而是定向到 Azure 的 URL SignalR 服务。

当 SignalR 托管在应用服务器上时,此集线器可以工作:

[Authorize(Roles = "Manager, Seller")]
public class CalendarHub : Hub<ICalendarClient> {
    private IHttpContextAccessor httpContextAccessor;
    public CalendarHub(IHttpContextAccessor httpContextAccessor) { this.httpContextAccessor = httpContextAccessor } 

    public override async Task OnConnectedAsync() {
        await Groups.AddToGroupAsync(Context.ConnectionId, GetClaimValue("OrganizationId"));
        await base.OnConnectedAsync();
    }

    private string GetClaimValue(string claimType) {
        var identity = (ClaimsIdentity)httpContextAccessor?.HttpContext?.User.Identity;
        var claim = identity?.FindFirst(c => c.Type == claimType);

        if (claim == null)
            throw new InvalidOperationException($"No claim of type {claimType} found.");

        return claim.Value;
    }
}

但是当我切换到 Azure 解决方案时:

//From: Startup.cs (abridged)
public IServiceProvider ConfigureServices(IServiceCollection services)
    services.AddSignalR().AddAzureSignalR();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime applicationLifetime) {
    app.UseAzureSignalR(routes => routes.MapHub<CalendarHub>("/signalr/calendar"));
}

...连接到集线器会导致异常未找到 OrganizationId 类型的声明。,因为身份完全为空,就好像没有用户经过身份验证一样。鉴于我限制了特定角色的用户的访问权限,这尤其奇怪。

最佳答案

结果错误与 this question 相同其中 HttpContext 用于获取声明值,因为这就是我们在其他地方所做的事情。只要应用服务本身处理与客户端的连接,这似乎就可以工作。

但是 Azure SignalR 服务在其他地方提供了声明:

正确的方法是仅使用从 SignalR Hub 访问时具有类型 HubCallerContextContext。所有 claim 均可从此处获得,无需额外工作。

因此获取声明的方法变为

private string GetClaimValue(string claimType) {
    var identity = Context.User.Identity;
    var claim = identity.FindFirst(c => c.Type == claimType);

    if (claim == null)
        throw new InvalidOperationException($"No claim of type {claimType} found.");

    return claim.Value;
}

关于具有承载身份验证的 Azure SignalR 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63337412/

相关文章:

azure - 禁止在 Azure Webjobs ("Executing: ' xxx' 中进行日志记录,因为在 'yyy' 上检测到新队列消息。”)

azure - 找不到 SQL Server 的防火墙设置

asp.net-mvc - 如何使用依赖注入(inject)将 UserId/TenantId 传递给存储库构造函数?

OAuth2 访问 token 格式

android - 在 Android 上使用 FirebaseUI 的 GitHub oAuth

c# - C# 中的 Azure Function App 是否可以执行命令行应用程序?

Azure 自动缩放不起作用

c# - Asp .Net Core 为什么即使用户未通过身份验证也会调用我的授权处理程序?

c# - .NET Core 中是否有 HtmlTableRow 的模拟

javascript - Google 联系人到下拉列表