identity: get correct remote address in case of auth failure
This commit is contained in:
@@ -18,6 +18,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Ng.Services;
|
||||
|
||||
@@ -25,18 +27,39 @@ namespace Microsoft.AspNetCore.Http
|
||||
{
|
||||
public static class HttpContextExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Get remote ip address, optionally allowing for x-forwarded-for header check
|
||||
/// </summary>
|
||||
/// <param name="context">Http context</param>
|
||||
/// <param name="allowForwarded">Whether to allow x-forwarded-for header check</param>
|
||||
/// <returns>IPAddress</returns>
|
||||
public static IPAddress GetRemoteIPAddress(this HttpContext context, bool allowForwarded = true)
|
||||
{
|
||||
if (allowForwarded)
|
||||
{
|
||||
// if you are allowing these forward headers, please ensure you are restricting context.Connection.RemoteIpAddress
|
||||
// to cloud flare ips: https://www.cloudflare.com/ips/
|
||||
string header = (context.Request.Headers["CF-Connecting-IP"].FirstOrDefault() ?? context.Request.Headers["X-Forwarded-For"].FirstOrDefault());
|
||||
if (IPAddress.TryParse(header, out IPAddress ip))
|
||||
{
|
||||
return ip;
|
||||
}
|
||||
}
|
||||
return context.Connection.RemoteIpAddress;
|
||||
}
|
||||
|
||||
static UserAgentService userAgentService = new UserAgentService();
|
||||
public static string GetClientInfo(this HttpContext httpContext)
|
||||
{
|
||||
var clientIp = httpContext.Connection.RemoteIpAddress;
|
||||
var clientIp = httpContext.GetRemoteIPAddress().ToString();
|
||||
var country = httpContext.Request.Headers["CF-IPCountry"];
|
||||
var userAgent = httpContext.Request.Headers["User-Agent"];
|
||||
var builder = new StringBuilder();
|
||||
|
||||
builder.AppendLine($"Date: {DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")}");
|
||||
|
||||
if (clientIp != null)
|
||||
builder.AppendLine($"IP: {clientIp.ToString()}");
|
||||
if (!string.IsNullOrEmpty(country))
|
||||
builder.AppendLine($"IP: {clientIp}");
|
||||
|
||||
if (!string.IsNullOrEmpty(country))
|
||||
builder.AppendLine($"Country: {country.ToString()}");
|
||||
|
||||
@@ -173,7 +173,7 @@ namespace Streetwriters.Identity
|
||||
{
|
||||
app.UseForwardedHeaders(new ForwardedHeadersOptions
|
||||
{
|
||||
ForwardedForHeaderName = "CF_CONNECTING_IP",
|
||||
ForwardedForHeaderName = "CF-Connecting-IP",
|
||||
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user