Skip to content

Commit

Permalink
Consider X-Forwarded-For for IP because we used app.UseForwardedHeade…
Browse files Browse the repository at this point in the history
…rs(); for Reverse Proxy
  • Loading branch information
infofromca committed Oct 8, 2024
1 parent de60815 commit f203ea5
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ private async Task<string> GetClientIpAddressAsync()
return null;
}

return (await _clientIPAddressAccessor.GetIPAddressAsync())?.ToString();
return (await _clientIPAddressAccessor.GetIPAddressAsync());
}

private async Task<AuditTrailSettings> GetAuditTrailSettingsAsync() =>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System.Net;

namespace OrchardCore;

public interface IClientIPAddressAccessor
{
Task<IPAddress> GetIPAddressAsync();
Task<string> GetIPAddressAsync();
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ private string GetIpAddressCacheKey()
{
var address = _clientIpAddressAccessor.GetIPAddressAsync().GetAwaiter().GetResult();

return $"{IpAddressAbuseDetectorCacheKey}:{address?.ToString() ?? string.Empty}";
return $"{IpAddressAbuseDetectorCacheKey}:{address ?? string.Empty}";
}

public RobotDetectionResult DetectRobot()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,32 @@ public DefaultClientIPAddressAccessor(IHttpContextAccessor httpContextAccessor)
_httpContextAccessor = httpContextAccessor;
}

public Task<IPAddress> GetIPAddressAsync()
public Task<string> GetIPAddressAsync()
{
var address = _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress;

if (address != null)
string ip = null;
// Check for X-Forwarded-For header
var forwardedFor = _httpContextAccessor.HttpContext?.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (!string.IsNullOrEmpty(forwardedFor))
{
// The client IP will be the first IP in the list
ip = forwardedFor.Split(',')[0].Trim();
}
else
{
if (IPAddress.IsLoopback(address))
// If X-Forwarded-For is not available, use the remote IP address
var address = _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress;

if (address != null)
{
address = IPAddress.Loopback;
if (IPAddress.IsLoopback(address))
{
address = IPAddress.Loopback;
}

ip = address.ToString();
}
}

return Task.FromResult(address);
return Task.FromResult(ip);
}
}

0 comments on commit f203ea5

Please sign in to comment.