c# - SignalR dotnet 核心认证

标签 c# asp.net-core asp.net-core-signalr

我正在使用 Microsoft.AspNetCore.SignalR带有 Bazinga.AspNetCore.Authentication.Basic 的 nuget 包它将基本身份验证添加到 dotnet 核心。我的 C# SignalR 客户端在没有身份验证时连接,但是当我添加 AuthorizeAttribute 时,它通过 http 连接并且 http 请求 header 已成功通过身份验证,但 Socket 未进行身份验证可能是因为套接字消息中没有 header 。

所以我想知道我应该如何将 token 或其他东西传递给经过身份验证的套接字连接,或者是否有我可以遵循的示例代码。我认为我应该将随机 token 传递给经过身份验证的用户,而用户需要不断地在消息中传递 token 。

Client project , Server project

服务器:

using System.Threading.Tasks;
using Bazinga.AspNetCore.Authentication.Basic;
using Domainlogic;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace API
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
            {
                builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowAnyOrigin();
            }));

            services.AddSignalR();

            services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
                .AddBasicAuthentication(credentials => Task.FromResult(
                    credentials.username == "SomeUserName"
                    && credentials.password == "SomePassword"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors("CorsPolicy");

            app.UseCors(CorsConstants.AnyOrigin);

            app.UseFileServer();

            app.UseSignalR(route => { route.MapHub<MessageHub>("/chat"); });

            app.UseAuthentication();
        }
    }
}

服务器中心:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;

namespace Domainlogic
{
    public class MessagePayload
    {
        public string Name { get; set; }

        public string Message { get; set; }

        public DateTime Date { get; set; }        
    }

    [Authorize]
    public class MessageHub : Hub
    {   
        // connected IDs
        private static readonly HashSet<string> ConnectedIds = new HashSet<string>();

        public override async Task OnConnectedAsync()
        {
            ConnectedIds.Add(Context.ConnectionId);

            await Clients.All.SendAsync("SendAction", "joined", ConnectedIds.Count);
        }

        public override async Task OnDisconnectedAsync(Exception ex)
        {
            ConnectedIds.Remove(Context.ConnectionId);

            await Clients.All.SendAsync("SendAction", "left", ConnectedIds.Count);
        }

        public async Task Send(MessagePayload message)
        {
            await Clients.All.SendAsync("SendMessage", message);
        }
    }
}

客户:

using System;
using System.Net;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Connections.Client;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;

namespace SignalRClient
{
    public class MessagePayload
    {
        public string Name { get; set; }

        public string Message { get; set; }

        public DateTime Date { get; set; }        
    }

    class Program
    {
        public static string Base64Encode(string plainText) {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }

        static void Main(string[] args)
        {
            var credential = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("SomeUserName" + ":" + "SomePassword"));

            //Set connection
            var connection = new HubConnectionBuilder()
                .WithUrl("http://localhost:5000/chat", options =>
                {
                    options.Headers.Add("Authorization", $"Basic {credential}");
                })
                .AddJsonProtocol()
                .Build();

            connection.On<MessagePayload>("SendMessage", param =>
            {
                Console.WriteLine(param.Message);
            });

            connection.StartAsync().Wait();

            var startTimeSpan = TimeSpan.Zero;
            var periodTimeSpan = TimeSpan.FromSeconds(3);
            int i = 0;

            var timer = new System.Threading.Timer((e) =>
            {
                connection.InvokeAsync<MessagePayload>("Send", new MessagePayload()
                {
                    Message = "Some message: " + i++
                });
            }, null, startTimeSpan, periodTimeSpan);


            Console.Read();
            connection.StopAsync();
        }
    }
}

最佳答案

感谢 GitHub 上的“davidfowl”,解决方案是将 UseAuthentication 移动到 UseSignalR 之上。

来源:https://github.com/aspnet/SignalR/issues/2316

代替:

app.UseSignalR(route => { route.MapHub<MessageHub>("/chat"); });

app.UseAuthentication();

使用这个:

app.UseAuthentication();

app.UseSignalR(route => { route.MapHub<MessageHub>("/chat"); });

关于c# - SignalR dotnet 核心认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50413788/

相关文章:

c# - 如何调试 ProtectKeysWithAzureKeyVault?

c# - 使用引用 token 进行 ASPNETCore SignalR 身份验证

c# - 查看 C# 编译器预编译了哪些代码

c# - 使用 linq 和 Entity Framework 创建适当的模型

c# - 尝试从第三方api同步数据

visual-studio - 在带有.NET Core项目的Visual Studio中将文件显示在其他文件之下

c# - SignalR 测试 - 如何在新版本的 SignalR for ASP.NET Core 2 中模拟组

带有 MessagePack 的 SignalR .Net 客户端 - IHubConnectionBuilder 中无法识别 AddMessagePackProtocol 方法

c# - 单声道:无法加载文件或程序集 'System.Threading.Tasks.Dataflow'

c# - 如何对 GridView 进行排序?