我正在尝试在信号记录器记录器集线器中实现jwt令牌。 但不知何故,我一直收到未经授权的回复
JS
let url = '/hub/log?token='+getToken();
let http = new this.$signalR.HttpConnection(url, options);
this.connection = new this.$signalR.HubConnection(http);
C#ConfigureServices
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
if (context.Request.Path.ToString().StartsWith("/hub/"))
{
context.Token = context.Request.Query["token"];
}
return Task.CompletedTask;
}
};
options.TokenValidationParameters =
new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = settings.JwtValidIssuer,
ValidAudience = settings.JwtValidAudience,
IssuerSigningKey = JwtSecurityKey.Create(settings.JwtSecurityKey)
};
});
调试器正在崩溃
context.Token = context.Request.Query["token"];
并设置context.Token
C#Hub
[Authorize(Roles = "Admin")]
public class LoggerHub : Hub
{
private readonly IServerManager serverManager;
public LoggerHub(IServerManager serverManager)
{
this.serverManager = serverManager;
}
[Authorize(Roles = "Admin")]
public override Task OnConnectedAsync()
{
serverManager.Logger.Log(Shared.Logging.LogLevel.Info, "New websocket connection");
return base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception exception)
{
serverManager.Logger.Log(Shared.Logging.LogLevel.Info, "a Socket disconnected");
return base.OnDisconnectedAsync(exception);
}
}
我做错了什么?
提前致谢
答案 0 :(得分:0)
Personnaly我在设置令牌之前检查了类似的请求类型
o.Events = new JwtBearerEvents //For signalR
{
OnMessageReceived = context =>
{
if (context.HttpContext.WebSockets.IsWebSocketRequest || context.Request.Headers["Accept"] == "text/event-stream")
{
StringValues accessToken = context.Request.Query["token"];
if (!string.IsNullOrEmpty(accessToken))
context.Token = accessToken;
}
return Task.CompletedTask;
}
};