首页 > 解决方案 > 我们如何使用跨域调用来验证 signalR?

问题描述

我正在使用signalR的asp.net apis项目,我想使用授权属性进行身份验证。为此,我发送jwt令牌并将此令牌添加到signalR管道中。首先我调用Apis获取令牌。然后我发送此令牌获得signalR连接,但signalR返回未经授权的响应。

The below is my code,


app.Map("/signalr", map =>
                {
                    // Setup the CORS middleware to run before SignalR.
                    // By default this will allow all origins. You can 
                    // configure the set of origins and/or http verbs by
                    // providing a cors options with a different policy.
                    map.UseCors(CorsOptions.AllowAll);

                    // SignalR Auth0 custom configuration.
                    map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
                    {
                        Provider = new OAuthBearerAuthenticationProvider()
                        {
                            OnRequestToken = context =>
                            {
                                if (context.Request.Path.Value.StartsWith("/signalr"))
                                {
                                    string bearerToken = context.Request.Query.Get("access_token");
                                    if (bearerToken != null)
                                    {
                                        string[] authorization = new string[] { "bearer " + bearerToken };
                                        context.Request.Headers.Add("Authorization", authorization);
                                    }
                                }

                                return null;
                            }
                        }
                    });


                    var hubConfiguration = new HubConfiguration
                    {
                        // You can enable JSONP by uncommenting line below.
                        // JSONP requests are insecure but some older browsers (and some
                        // versions of IE) require JSONP to work cross domain
                        // EnableJSONP = true
                    };
                    // Run the SignalR pipeline. We're not using MapSignalR
                    // since this branch already runs under the "/signalr"
                    // path.
                    map.RunSignalR(hubConfiguration);
                });
                app.UseWebApi(config);
                GlobalHost.DependencyResolver.Register(
            typeof(SignalRHUB),
            () => new SignalRHUB(new UnitOfWork(new DbFactory())));
                //GlobalHost.HubPipeline.RequireAuthentication();
                //app.MapSignalR();

标签: apisignalrjwt

解决方案


推荐阅读