打开 关闭

How to use a custom HTTP header to get the client remote IP address? #1950


User avatar
0
alper 创建
支持团队 Director

My website is behind a proxy server / load balancer and the client ip is passed in a custom HTTP header. To get the Identity Server work, we need to use the custom HTTP header. The client IP is stored in X-Original-Host HTTP header.


1 答案
  • User Avatar
    0
    alper 创建
    支持团队 Director

    Create the below extension class in your web project. Set the ForwardedHeaderName to whatever HTTP header the real IP address is in.

    public static class ApplicationBuilderExtensions
    {
        public static IApplicationBuilder UseCustomHttpHeaders(this IApplicationBuilder builder)
        {
            var options = new ForwardedHeadersOptions
            {
                ForwardedForHeaderName = ForwardedHeadersDefaults.XOriginalHostHeaderName,  //"X-Original-Host"
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            };
    
            options.KnownNetworks.Clear();
            options.KnownProxies.Clear();
    
            return builder.UseForwardedHeaders(options);
        }
    }
    

    Open your web module class.

     public override void OnApplicationInitialization(ApplicationInitializationContext context)
    {
        var app = context.GetApplicationBuilder();
        var env = context.GetEnvironment();
    
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseCustomHttpHeaders();
        }
        else
        {
            app.UseErrorPage();
            app.UseCustomHttpHeaders();
            app.UseHsts();
    
            app.UseAllElasticApm(context.GetConfiguration());
        }
    
        //...
    

    Create a simple controller to test it.

    public class Test : Controller
    {
        public string Index()
        {
            return "Client IP Address: " + HttpContext.Connection.RemoteIpAddress.ToString();
        }
    }
    

    Open Postman and make a GET request to TestController

    PS: If you want to use X-Forwarded-For header, then remove ForwardedForHeaderName = "X-Original-Host" .

    References:

    • https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer
    • https://github.com/IdentityServer/IdentityServer4/blob/main/src/IdentityServer4/src/Endpoints/DiscoveryEndpoint.cs#L53
    • https://github.com/IdentityServer/IdentityServer4/blob/main/src/IdentityServer4/src/Extensions/HttpContextExtensions.cs#L108
    • https://github.com/IdentityServer/IdentityServer4/blob/main/src/IdentityServer4/src/Extensions/HttpContextExtensions.cs#L88
Made with ❤️ on ABP v8.2.0-preview Updated on 三月 25, 2024, 15:11