Microsoft.Identity.Web和ASP.NET Core SignalR JWT身份验证 [英] Microsoft.Identity.Web and ASP.NET Core SignalR JWT authentication
本文介绍了Microsoft.Identity.Web和ASP.NET Core SignalR JWT身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用ASP.NET Core制作一个Web应用程序,该应用程序也使用SignalR Core来提供实时功能。我使用Azure AD B2C进行用户管理。我已成功使用Microsoft.Identity.Web
(https://github.com/AzureAD/microsoft-identity-web)通过Azure AD B2C生成的令牌保护我的API终结点。
我想对我的SignalR核心集线器执行同样的操作。文档内容为向您的集线器/方法添加适当的注释,我已经这样做了。SignalR的客户端库将访问令牌作为查询参数添加,必须在ASP.NET核心应用程序的配置中手动提取该参数并将其添加到上下文中,如下所示。
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对象,而不是添加JwtBeader。
改编自本文档:https://github.com/AzureAD/microsoft-identity-web/wiki/customization
这篇关于Microsoft.Identity.Web和ASP.NET Core SignalR JWT身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文