Microsoft.Identity.Web和ASP.NET Core SignalR JWT身份验证

编程入门 行业动态 更新时间:2024-10-15 12:36:36
本文介绍了Microsoft.Identity.Web和ASP.NET Core SignalR JWT身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用ASP.NET Core制作一个Web应用程序,该应用程序也使用SignalR Core来提供实时功能。我使用Azure AD B2C进行用户管理。我已成功使用Microsoft.Identity.Web(github/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。

改编自本文档:github/AzureAD/microsoft-identity-web/wiki/customization

更多推荐

Microsoft.Identity.Web和ASP.NET Core SignalR JWT身份验证

本文发布于:2023-11-17 02:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608539.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:身份验证   Web   ASP   Microsoft   Identity

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!