什么是默认Javascript SignalR客户端身份验证方案?

时间:2018-09-15 18:06:53

标签: asp.net-core-signalr

我的SignalR应用程序有两个客户端:用于Web浏览器的Javascript客户端和使用JWT承载身份验证的Android客户端(manual page of access() )。

我将此属性添加到了SignalR Hub:

birthday = input("birthday").split()
a = ''.join([''.join([i for i in c if i.isdigit()][-2:]) for c in birthday])

和我的 Startup.cs 文件:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme + "," + CookieAuthenticationDefaults.AuthenticationScheme)]
public class MyHub : Hub

使用标头身份验证承载令牌成功登录Android客户端。 但是,Web客户端无法连接到集线器(401未经授权)。

当我删除[Authorize]属性时,javascript客户端可以正常工作!

什么是默认Javascript SignalR客户端身份验证方案?还是我遇到的问题是什么?

我使用dotnet core 2.1,Microsoft.AspNetCore.SignalR,而我的IDE是Mac的Visual Studio。

1 个答案:

答案 0 :(得分:0)

来自SignalR docs

在标准 Web API 中,不记名令牌在 HTTP 标头中发送。但是,SignalR 在使用某些传输时无法在浏览器中设置这些标头。使用 WebSockets 和 Server-Sent Events 时,令牌作为查询字符串参数传输。

services.AddAuthentication(options =>
        {
            // ...
        })
        .AddJwtBearer(options =>
        {
            // ...

            // We have to hook the OnMessageReceived event in order to
            // allow the JWT authentication handler to read the access
            // token from the query string when a WebSocket or 
            // Server-Sent Events request comes in.

            // Sending the access token in the query string is required due to
            // a limitation in Browser APIs. We restrict it to only calls to the
            // SignalR hub in this code.
            // See https://docs.microsoft.com/aspnet/core/signalr/security#access-token-logging
            // for more information about security considerations when using
            // the query string to transmit the access token.
            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    var accessToken = context.Request.Query["access_token"];

                    // If the request is for our hub...
                    var path = context.HttpContext.Request.Path;
                    if (!string.IsNullOrEmpty(accessToken) &&
                        (path.StartsWithSegments("/hubs/chat")))
                    {
                        // Read the token out of the query string
                        context.Token = accessToken;
                    }
                    return Task.CompletedTask;
                }
            };
        });
相关问题