我们正在尝试扩展日历应用程序,该应用程序使用SignalR根据用户的OrganizationId
向客户端推送更新。以前,SignalR东西托管在单个App Server中,但是为了使其能够在多个服务器上运行,我们选择使用Azure SignalR Services。
但是,当应用程序使用Azure解决方案时,自动加密会中断。
在Startup.cs
中设置了身份验证,以在处理集线器端点时在url /查询字符串中查找令牌:
//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://docs.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
事件代码,这是有道理的,因为该请求不再针对App Service,而是针对Azure SignalR Service的URL。
当SignalR托管在App Server上时,此Hub可以工作:
[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"));
}
...连接到集线器会导致异常No claim of type OrganizationId found.
,因为identity
完全为空,就好像没有用户通过身份验证一样。鉴于我已限制访问特定角色的用户,所以这尤其奇怪。
答案 0 :(得分:1)
结果表明错误与this question相同,其中HttpContext
用于获取索赔值,因为这是我们在其他任何地方所做的。只要这是由App Service本身来处理与客户端的连接,这似乎就可以起作用。
但是Azure SignalR Service在其他地方提供了声明:
正确的方法是仅使用从SignalR集线器访问时类型为Context
的{{1}}。所有索赔都可以从这里获得,无需额外工作。
因此获取索赔的方法变为
HubCallerContext