SignalR (.NET Core) 中的 JWT 身份验证,无需在查询字符串中传递令牌 [英] JWT authentication in SignalR (.NET Core) without passing token in Query String

查看:19
本文介绍了SignalR (.NET Core) 中的 JWT 身份验证,无需在查询字符串中传递令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ASP .NET Core Web API 应用程序中使用 JWT 身份验证令牌.令牌由 API 本身生成,而不是由第三方生成.我成功地将 SignalR 添加到堆栈中,但现在我需要对尝试执行服务器(集线器)方法的用户进行身份验证.有人建议在 JavaScript 的qs"属性中传递令牌.这对我不起作用,因为我们的令牌非常大(它们包含很多声明).我尝试编写一个自定义中间件来从有效负载中读取令牌并自动验证用户.问题是,当使用 WebSockets 时,中间件没有被执行.任何想法都会有所帮助.

I am using JWT authentication tokens in an ASP .NET Core Web API application. The tokens are generated by the API itself, not by a third party. I added SignalR sucessfully to the stack, but now I need to authenticate the users that are trying to execute server (Hub) methods. Someone suggested to pass the token in the "qs" property in JavaScript. This will not work for me as our tokens are really large (they contain lots of claims). I tried writing a custom middleware for reading the token from the payload and auto-authenticating the user. The problem is that, when using WebSockets, the middleware is not executed. Any ideas will help.

推荐答案

看看建议使用查询字符串的文章 使用 JWT 对 ASP.NET Core 1.0 (vNext) SignalR 应用程序进行身份验证.我知道您的令牌太长,但作者解释了如何使用中间件对请求进行身份验证.

Have a look at article that suggests to use query string Authenticate against a ASP.NET Core 1.0 (vNext) SignalR application using JWT. I know that your token is too long, but author explains how to use middleware to authenticate the request.

这是文章的摘要:

  • SignalR 没有内置任何特殊的身份验证机制,它使用标准的 ASP.NET 身份验证.
  • JWT 通常在请求的 Authorization 标头中发送
  • SignalR JavaScript 客户端库不包含在请求中发送标头的方法,但它允许您传递查询字符串
  • 如果我们在查询字符串中传递令牌,我们可以编写一个中间件,添加一个以令牌作为其值的授权标头.这必须在管道中的 Jwt 中间件之前完成
  • 注意Bearer"格式

我已经强调了你的自定义中间件应该在 Jwt 中间件之前注册的关键点.

I have highlighted the key point that your custom middleware should be registered before Jwt middleware.

从此answer,您可以创建一个 WebSocket 连接并将您的令牌作为基本身份验证参数传递:

From this answer you can create a WebSocket connection and pass your token as basic auth parameter:

var ws = new WebSocket($"ws://{token}@example.com/service");

这篇关于SignalR (.NET Core) 中的 JWT 身份验证,无需在查询字符串中传递令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆