Base solution for your next web application
Open Closed

Audit logs using cloudflare`s IP instead of client #11169


User avatar
0
leonardocooper created

Angular+Core Project

The IP address logged on "Audit logs" and also on "Login attemps" is the IP from Cloudflare's service, and not the real user IP address.

The IP I need logged is in the http header "CF-Connecting-IP".

Is there a way to make the system get that IP for the user? Which class/method should I override to make this work?

Thank you, Leonardo C.


3 Answer(s)
  • User Avatar
    0
    rickfrankel created

    You need to override the GetClientIpAddress in the HttpContextClientInfoProvider.

    What I've done is have in the MyProject.Web.Core project in the Helpers folder I created my own class.

    `using Abp.AspNetCore.Mvc.Auditing; using Microsoft.AspNetCore.Http; using System;

    namespace MyProject.Web.Helpers { public class MyProjectHttpContextClientInfoProvider : HttpContextClientInfoProvider { private readonly IHttpContextAccessor _httpContextAccessor;

        public MyProjectHttpContextClientInfoProvider(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
    
        }
    
        protected override string GetClientIpAddress()
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
    
                if (httpContext?.Request?.Headers?.ContainsKey("Cf-Connecting-IP") ?? false)
                {
                    return httpContext.Request.Headers["Cf-Connecting-IP"];
                }
                else
                {
                    return httpContext?.Connection?.RemoteIpAddress?.ToString();
                }
    
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.ToString());
            }
            return null;
        }
    }
    

    } `

    Then you need to tell the system to use your class.

    In the MyProjectWebCoreModule.cs file in the same project.

    Add this line at the end of PreInitialize

    `Configuration.ReplaceService<IClientInfoProvider, MyProjectHttpContextClientInfoProvider>(DependencyLifeStyle.Transient);

  • User Avatar
    0
    leonardocooper created

    Worked like a charm. Thank you

    I added a small change to call the base method in case it dont find the header.

    `protected override string GetClientIpAddress() { try { var httpContext = _httpContextAccessor.HttpContext;

        if (httpContext?.Request?.Headers?.ContainsKey("CF-Connecting-IP") ?? false)
        {
            return httpContext.Request.Headers["CF-Connecting-IP"];
        }
    
    }
    catch (Exception ex)
    {
        Logger.Warn(ex.ToString());
    }
    
    return base.GetClientIpAddress();
    

    }`

  • User Avatar
    0
    rickfrankel created

    Excellent update. I've added that into mine as well.