本文介绍了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.

推荐答案

看看建议使用查询字符串使用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.

这是文章的摘要:

我强调了一个关键点,即您的自定义中间件应在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身份验证,而无需在查询字符串中传递令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 03:10