dotnet 核心 SignalR 身份验证

问题描述 投票:0回答:1

我正在尝试创建一个应用程序,使用微服务架构向授权客户端提供 Api 方法和 SignalR 集线器连接。我们将引用令牌与身份服务器一起使用。 Identity Server 是另一个项目并且独立运行,因此我的应用程序必须通过 Identity Server 授权用户并获取他的声明。 当客户端尝试启动套接字连接时,我收到错误。

服务器:

services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder => builder
                .WithOrigins("https://localhostClientUrl")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
            });

services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme)
            .AddOAuth2Introspection(options =>
            {
                options.Authority = "https://identityserverURL";
                options.ClientId = "client";
                options.ClientSecret = "secret";
                options.Events = new OAuth2IntrospectionEvents
                { 
                    OnTokenValidated = async context =>
                    {
                        var path = context.HttpContext.Request.Path;

                        var accessToken = context.Request.Query["access_token"];

                        if (!string.IsNullOrEmpty(accessToken) &&
                            (path.StartsWithSegments(Configuration["MapHub"])))
                        {
                            // Read the token out of the query string
                            context.SecurityToken = accessToken;
                        }
                        await Task.CompletedTask;
                    }
                };
            });

还有

app.UseCors("CorsPolicy");

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints => {
   endpoints.MapControllers();
   endpoints.MapRazorPages();
   endpoints.MapHub<ChatHub>(Configuration["MapHub"]);
});

客户:

this.hubConnection = new signalR.HubConnectionBuilder()
         .withUrl(this.hubUrl, { accessTokenFactory: () => "ReferenceToken" })
         .withAutomaticReconnect()
         .build();

this.hubConnection
            .start()
            .then(() => {
               return true;
            })
            .catch((err) => {
               return false;
            });

客户端连接成功,可以获取当前连接的 HttpContext.User 上的所有声明。之前成功连接我收到许多客户端错误:

WebSocket connection to 'wss://localhost:2222/myHub?id=ew5CRILwAiTZ955IXCZEkg&access_token=C11235C6ADEA27B5EABC08762E1A1B65077278714' failed: HTTP Authentication failed; no valid credentials available

Error: Failed to start the transport 'WebSockets': Error: WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.

GET https://localhost:2222/myHub?id=XaHhJ66drE0tfIlI3-_OPA&access_token=C11235C6ADEA27B5EABC08762E1A1B65077278714 401

Error: Failed to start the transport 'ServerSentEvents': Error: EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled.

有什么想法吗?我看到客户端正在向服务器发送 /myHub/negotiate 请求。另外 OnTokenValidated context.Request.Query["access_token"] 为空。我想念什么?

如果我更改 AddOAuth2Introspection 并使用已弃用的 AddIdentityServerAuthentication,则可以正常工作,不会出现任何客户端错误。

.AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme, options =>
            {
                // base-address of your identityserver
                options.Authority ="https://identityserverURL";
                options.ApiName = "apiname";
                options.ApiSecret = "secret";
                options.RequireHttpsMetadata = false;
                options.TokenRetriever = new Func<HttpRequest, string>(req =>
                {
                    var fromHeader = TokenRetrieval.FromAuthorizationHeader();
                    var fromQuery = TokenRetrieval.FromQueryString();
                    return fromHeader(req) ?? fromQuery(req);
                });
            });

谢谢你

.net-core authorization signalr
1个回答
0
投票

你有没有弄清楚这一点?我有确切的问题,我觉得我已经尝试了您在这里发布的所有内容。

© www.soinside.com 2019 - 2024. All rights reserved.