繁体   English   中英

SignalR dotnet核心认证

[英]SignalR dotnet core authentication

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

所以我想知道如何将令牌或其他内容传递给经过身份验证的套接字连接,或者是否有我可以遵循的示例代码。 我想我应该将一个随机令牌传递给经过身份验证的用户,并且用户需要不断地在消息中传递令牌。

客户端项目服务器项目

服务器:

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"); });

为了解决这个问题,我不得不在服务器缓存中存储带有connectionId的用户令牌。 那是因为在集线器中我无法控制会话。

因此,每次用户与我公开的集线器连接时,以及接收connectionId和用户令牌的端点。 当Hub处理请求时,我知道连接是用户认证的。

调节器

[HttpPost]
[Authorize]
[Route("{connectionId}")]
public IActionResult Post(string connectionId)
{
    this.hubConnectionService.AddConnection(connectionId, this.workContext.CurrentUserId);
    return this.Ok();
}

public override Task OnDisconnectedAsync(Exception exception)
{
    this.hubConnectionService.RemoveConnection(this.Context.ConnectionId);
    return base.OnDisconnectedAsync(exception);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM