【发布时间】:2020-01-14 20:42:45
【问题描述】:
所以我想要完成的是,当用户发送消息时,在服务器端我想知道哪些“其他”连接可用。我正在使用 SignalR。
从这些连接中,我想知道与每个连接关联的用户的角色。
我正在使用 ASP.NET Identity、SignalR 和 C#。
然后我想根据用户角色过滤掉连接并仅向这些用户广播消息。
任何想法如何实现。
【问题讨论】:
标签: javascript c# asp.net signalr
所以我想要完成的是,当用户发送消息时,在服务器端我想知道哪些“其他”连接可用。我正在使用 SignalR。
从这些连接中,我想知道与每个连接关联的用户的角色。
我正在使用 ASP.NET Identity、SignalR 和 C#。
然后我想根据用户角色过滤掉连接并仅向这些用户广播消息。
任何想法如何实现。
【问题讨论】:
标签: javascript c# asp.net signalr
我认为你可以使用这个article 来做到这一点
基本上,您可以将令牌从客户端发送到服务器(在本例中为 JWT)。 JWT 可以包含您需要的所有信息。
您提供的访问令牌函数在每个 HTTP 之前调用 SignalR 提出的请求。如果您需要更新令牌以 保持连接处于活动状态(因为它可能会在 连接),在此函数中执行此操作并返回更新的 令牌。
这意味着当用户调用 signalr 时,他们将在集线器中再次进行身份验证。
或者您可以向用户添加声明,以便您可以检测谁请求以及他们具有什么角色
文档示例:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(options =>
{
// Identity made Cookie authentication the default.
// However, we want JWT Bearer Auth to be the default.
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
// Configure JWT Bearer Auth to expect our security key
options.TokenValidationParameters =
new TokenValidationParameters
{
LifetimeValidator = (before, expires, token, param) =>
{
return expires > DateTime.UtcNow;
},
ValidateAudience = false,
ValidateIssuer = false,
ValidateActor = false,
ValidateLifetime = true,
IssuerSigningKey = SecurityKey
};
// We have to hook the OnMessageReceived event in order to
// allow the JWT authentication handler to read the access
// token from the query string when a WebSocket or
// Server-Sent Events request comes in.
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;
}
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSignalR();
// Change to use Name as the user identifier for SignalR
// WARNING: This requires that the source of your JWT token
// ensures that the Name claim is unique!
// If the Name claim isn't unique, users could receive messages
// intended for a different user!
services.AddSingleton<IUserIdProvider, NameUserIdProvider>();
// Change to use email as the user identifier for SignalR
// services.AddSingleton<IUserIdProvider, EmailBasedUserIdProvider>();
// WARNING: use *either* the NameUserIdProvider *or* the
// EmailBasedUserIdProvider, but do not use both.
}
【讨论】: