get actual IP from connection

This commit is contained in:
Stanley Dimant
2022-08-03 19:42:02 +02:00
parent d5b7dd69e8
commit 9e0ac74de7
2 changed files with 28 additions and 3 deletions

View File

@@ -0,0 +1,24 @@
using Microsoft.AspNetCore.Http;
namespace MareSynchronosServer
{
public static class Extensions
{
public static string GetIpAddress(this IHttpContextAccessor accessor)
{
if (!string.IsNullOrEmpty(accessor.HttpContext.Request.Headers["CF-CONNECTING-IP"]))
return accessor.HttpContext.Request.Headers["CF-CONNECTING-IP"];
var ipAddress = accessor.HttpContext.GetServerVariable("HTTP_X_FORWARDED_FOR");
if (!string.IsNullOrEmpty(ipAddress))
{
var addresses = ipAddress.Split(',');
if (addresses.Length != 0)
return addresses.Last();
}
return accessor.HttpContext.Connection.RemoteIpAddress.ToString();
}
}
}

View File

@@ -8,6 +8,7 @@ using MareSynchronosServer.Authentication;
using MareSynchronosServer.Data; using MareSynchronosServer.Data;
using MareSynchronosServer.Metrics; using MareSynchronosServer.Metrics;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@@ -33,7 +34,7 @@ namespace MareSynchronosServer.Hubs
} }
[HubMethodName(Api.InvokeHeartbeat)] [HubMethodName(Api.InvokeHeartbeat)]
public async Task<ConnectionDto> Heartbeat(string? characterIdentification) public async Task<ConnectionDto> Heartbeat(string characterIdentification)
{ {
MareMetrics.InitializedConnections.Inc(); MareMetrics.InitializedConnections.Inc();
@@ -86,8 +87,8 @@ namespace MareSynchronosServer.Hubs
public override Task OnConnectedAsync() public override Task OnConnectedAsync()
{ {
var feature = Context.Features.Get<IHttpConnectionFeature>(); var feature = Context.Features.Get<IHttpContextAccessor>();
_logger.LogInformation("Connection from " + feature.RemoteIpAddress); _logger.LogInformation("Connection from " + feature.GetIpAddress());
MareMetrics.Connections.Inc(); MareMetrics.Connections.Inc();
return base.OnConnectedAsync(); return base.OnConnectedAsync();
} }