SignalR JWT Authorize

使用SignalR时,如果需要增加JWT token 需要在客户端将access_toke传入,然后在服务端将token设置到context中,服务端代码:

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(“Bearer”, options =>
{
options.Authority = “https://localhost:5001”;

            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = false
            };

            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("/chat")))
                    {
                        // Read the token out of the query string
                        context.Token = accessToken;
                    }
                    return Task.CompletedTask;
                }
            };
        });

客户端代码:
connection = new signalR.HubConnectionBuilder().withUrl(“http://host.docker.internal:5189/gameCenterHub”,
{
accessTokenFactory: () => user.access_token
}).build();

© 版权声明

相关文章

暂无评论

none
暂无评论...