我正在使用 ASP.NET Core 制作一个 Web 应用程序,该应用程序还使用 SignalR Core 来提供实时功能。我使用 Azure AD B2C 进行用户管理。我已成功使用 Microsoft.Identity.Web
( https://github.com/AzureAD/microsoft-identity-web ) 使用 Azure AD B2C 生成的 token 来保护我的 API 终结点。
我想对我的 SignalR Core 集线器做同样的事情。该文档读取将适当的注释添加到您的集线器/方法中,我已经这样做了。 SignalR 的客户端库将访问 token 添加为查询参数,必须在 ASP.NET Core 应用程序的配置中手动提取该参数并将其添加到上下文中,如下所示。
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
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;
}
};
});
但是,这似乎与 Microsoft.Identity.Web
提供的配置不兼容,此处:
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAdB2C"));
如何使 SignalR 与 Microsoft.Identity.Web
配合使用?
最佳答案
应该可以做到:
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(configuration);
services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
Func<MessageReceivedContext, Task> existingOnMessageReceivedHandler = options.Events.OnMessageReceived;
options.Events.OnMessageReceived = async context =>
{
await existingOnMessageReceivedHandler(context);
StringValues accessToken = context.Request.Query["access_token"];
PathString path = context.HttpContext.Request.Path;
// If the request is for our hub...
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
{
// Read the token out of the query string
context.Token = accessToken;
}
};
});
您可以通过这种方式配置 JwtBearerOptions 对象,而不是添加 JwtBearer。
改编自本文档:https://github.com/AzureAD/microsoft-identity-web/wiki/customization
关于azure - Microsoft.Identity.Web 和 ASP.NET Core SignalR JWT 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65209097/