SignalR身份验证问题



我正在开发一个ASP.NET核心应用程序,需要实现与SignalR的聊天。我使用Identity和jwt来管理登录/权限,这很好。

我遵循了这些文档在SignalR集线器中实现身份验证,但它不起作用,即使使用集线器上的[Authorize]属性也可以访问我的集线器功能。

这是我配置服务的代码

services
.AddAuthorization()
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = jwtSettings.Issuer,
ValidAudience = jwtSettings.Issuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Secret)),
ClockSkew = TimeSpan.Zero
};
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("/chat")))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});

这是我的集线器的代码

[Authorize]
public class Chat : Hub<IChatClientMethods>
{
private readonly ProjectHubContext _context;
private readonly UserManager<User> _userManager;
public Chat(ProjectHubContext context, UserManager<User> userManager) : base()
{
_context = context;
_userManager = userManager;
}

// This method is executed even with the [Authorize] attribute
public override async Task OnConnectedAsync()
{
await base.OnConnectedAsync();
Console.WriteLine("Connected");
var user = await _userManager.GetUserAsync(Context.User); //Always null
}
}

最后是集线器映射

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<Chat>("/chat");
});

当我提供随机测试令牌时,为什么我可以从客户端调用集线器函数?

我发现了我的[Authorize]标记不起作用的原因。

我用错了用法。我使用了using MiNET.Plugins.Attributes;而不是using Microsoft.AspNetCore.Authorization;

相关内容

  • 没有找到相关文章

最新更新