Files
BeWoPlaner/Service/ServiceBehavior/AdminServiceMessageInspector.cs
2025-09-18 16:59:24 +02:00

59 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using BeWo.Data;
using BeWo.Service.Core;
namespace BeWo.Service.ServiceBehavior
{
public class AdminServiceMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
// Hole die erlaubte IP aus den appSettings
string allowedIP = ConfigurationManager.AppSettings["AdminServiceIPAddress"];
string allowedIP2 = ConfigurationManager.AppSettings["AdminServiceIPAddress2"];
// Extrahiere die RemoteEndpoint-IP-Adresse
string remoteIP = request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name)
? ((RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name]).Address
: null;
var allowed = string.Equals(remoteIP, allowedIP, StringComparison.OrdinalIgnoreCase);
var allowed2 = string.Equals(remoteIP, allowedIP2, StringComparison.OrdinalIgnoreCase);
// Vergleiche die IPs
if (remoteIP == null || !(allowed || allowed2))
{
throw new UnauthorizedAccessException($"Zugriff verweigert. Remote IP ({remoteIP ?? "Unbekannt"}) ist nicht erlaubt.");
}
// Hole erlaubten API Key aus den appSettings
string allowedApikey = MergedConfig.GetSetting("AdminServiceAPIKey");
// Extrahiert den API Key von Remote
var prop = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
var remoteApikey = prop?.Headers["admin-service-api-key"];
// Vergleicht die API Keys
if(remoteApikey == null || !string.Equals(remoteApikey, allowedApikey, StringComparison.Ordinal))
{
throw new UnauthorizedAccessException($"Zugriff verweigert. API Key ({remoteApikey ?? "Unbekannt"}) ist nicht erlaubt.");
}
return null; // Keine Zustandsinformationen erforderlich
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
// Keine zusätzliche Logik erforderlich vor dem Senden der Antwort
}
}
}