我正在使用 ASP.NET Core 制作一个 Web 应用程序,该应用程序还使用 SignalR Core 来提供实时功能。我使用 Azure AD B2C 进行用户管理。我已经成功使用了Microsoft.Identity.Web
(https://github.com/AzureAD/microsoft-identity-web)使用 Azure AD B2C 生成的令牌来保护我的 API 终结点。
我想对我的 SignalR Core 集线器做同样的事情。该文档读取将适当的注释添加到您的集线器/方法中,我已经这样做了。 SignalR 的客户端库将访问令牌添加为查询参数,必须在 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
, here:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)