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

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

问题描述

我在ASP .NET Core Web API应用程序中使用JWT身份验证令牌.令牌是由API本身而非第三方生成的. 我成功地将SignalR添加到了堆栈中,但是现在我需要对尝试执行服务器(Hub)方法的用户进行身份验证. 有人建议在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.

推荐答案

看看建议使用查询字符串

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中间件之前完成
  • 注意载体"格式
  • SignalR does not have any special authentication mechanism built in, it is using the standard ASP.NET authentication.
  • JWT is typically sent in the Authorization header of a request
  • The SignalR JavaScript client library does not include the means to send headers in the requests, it does however allow you to pass a query string
  • If we pass the token in the query string we can write a middleware that adds a authorization header with the token as its value. This must be done before the Jwt middleware in the pipeline
  • Be aware of the "Bearer " format

我强调了一个关键点,即您的自定义中间件应在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天全站免登陆