[英]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.