Add simple socket auth via stdin exchange

This commit is contained in:
rafael-aero
2021-12-23 09:24:29 +01:00
parent 546c617cd0
commit f229d540a8
4 changed files with 111 additions and 69 deletions

View File

@@ -425,6 +425,11 @@ namespace ElectronNET.API
{
if (_socket is null)
{
if(string.IsNullOrWhiteSpace(AuthKey))
{
throw new Exception("You must call Electron.ReadAuth() first thing on your main entry point.");
}
if (HybridSupport.IsElectronActive)
{
lock (_syncRoot)
@@ -448,8 +453,12 @@ namespace ElectronNET.API
socket.OnConnected += (_, __) =>
{
_connectedSocketEvent.Set();
Log("ElectronNET socket {1} connected on port {0}!", BridgeSettings.SocketPort, socket.Id);
Task.Run(async () =>
{
await socket.EmitAsync("auth", AuthKey);
_connectedSocketEvent.Set();
Log("ElectronNET socket {1} connected on port {0}!", BridgeSettings.SocketPort, socket.Id);
});
};
socket.OnReconnectAttempt += (_, __) =>
@@ -511,6 +520,7 @@ namespace ElectronNET.API
}
internal static ILogger<App> Logger { private get; set; }
internal static string AuthKey { private get; set; }
private class CamelCaseNewtonsoftJsonSerializer : NewtonsoftJsonSerializer
{

View File

@@ -1,5 +1,6 @@
using Microsoft.Extensions.Logging;
using System.Runtime.Versioning;
using System;
namespace ElectronNET.API
{
@@ -10,6 +11,23 @@ namespace ElectronNET.API
{
private static ILoggerFactory loggerFactory;
/// <summary>
/// Reads the auth key from the command line. This method must be called first thing.
/// </summary>
/// <exception cref="Exception"></exception>
public static void ReadAuth()
{
var line = Console.ReadLine();
if(line.StartsWith("Auth="))
{
BridgeConnector.AuthKey = line.Substring("Auth=".Length);
}
else
{
throw new Exception("The call to Electron.ReadAuth must be the first thing your app entry point does");
}
}
/// <summary>
/// Sets the logger factory to be used by Electron, if any
/// </summary>