【发布时间】:2020-06-04 19:58:39
【问题描述】:
尝试按照以下链接中的建议将 JWT 令牌传递到我的 SignalR 集线器,但到目前为止它不起作用。特别是,请参阅 David Fowler 在 2017 年 7 月 22 日的建议。https://github.com/aspnet/SignalR/issues/130
我的前端是React,所以我只是将令牌添加到查询字符串中,如下所示_token 具有我的JWT 令牌值:
const connection = new signalR.HubConnectionBuilder()
.withUrl("/myhub?AUTHORIZATION=" + _token)
.configureLogging(signalR.LogLevel.Information)
.build();
在我的Startup.cs 的ConfigureServices() 方法中,我对Jwt 令牌有以下配置:
services.AddAuthentication(options => {
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions => {
jwtOptions.Authority = $"https://login.microsoftonline.com/tfp/{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:Policy"]}/v2.0/";
jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"];
jwtOptions.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
if(context.HttpContext.WebSockets.IsWebSocketRequest)
context.Token = context.Request.Query["AUTHORIZATION"];
return Task.CompletedTask;
}
};
});
这就是我的Hub 的样子:
[Authorize]
public class MyHub : Hub
{
private IBackendService _backendService;
public MyHub(IBackendService backendService)
{
_backendService = backendService;
}
public async Task SendMessage(string message)
{
// Regular SignalR stuff
// SignalR will now send the message to all connected users...
}
}
基本上,我收到了401 Unauthorized 错误。
我设置了一个断点来检查请求是否是网络套接字请求,但我没有点击它。看起来管道中的某些东西正在确定用户未通过身份验证。
我在代码中做错了什么?
【问题讨论】:
-
看起来我们正在做一些类似的事情。如果您有任何其他问题,请在此处联系我。我很乐意提供帮助
-
@johnny5 非常感谢。对此,我真的非常感激。我还没有检查整个代码,但接受了你的解决方案作为答案,所以如果我有一些问题困扰你,请不要生我的气。
-
别担心,你可以随时打扰我,我会随时为您提供帮助,我最近刚刚经历了这些困难。
标签: signalr signalr-hub asp.net-core-signalr