简体   繁体   中英

How to get real client IP on gRPC Java server side using Nginx as reverse proxy

I use grpc-java as server backend and Nginx as load balancer between server and client, now I can get request Metadata like this

Metadata(content-type=application/grpc,user-agent=grpc-java-netty/1.12.0,grpc-accept-encoding=gzip,grpc-trace-bin=)

and client IP by Grpc.TRANSPORT_ATTR_REMOTE_ADDR like this

{remote-addr=/10.10.10.202:54031}

Obviously it's the local IP of Nginx node. I already set X-Real-IP and X-Forwarded-For in nginx.conf

...
server  {
    listen       50010 http2;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
...

these 2 keys should be present in request Metadata. Could anyone help me out? The version of gRPC is 1.12 and version of nginx is 1.15.2 on CentOS 7.4

In Java you can access all the headers by looking at the Metadata for the ServerCall. Metadata and headers are the same thing. Normally, the StreamObservers don't expose this to you, as most users don't care about headers.

In your case, you can use a ServerInterceptor to access the Metadata. The correct way to expose this is by pulling the correct header out of the Metadata and put it into the Context . The context is scoped to the ServerCall and can be accessed outside of the interceptor. In your server handler, you can call Context.current() and get the value you using the Context.Key you used to put the header in the context.

  1. config "grpc_set_header X-Real-IP $remote_addr;" nginx for grpc: grpc_set_header
server {
    listen  9099  http2;
    access_log    /var/log/nginx/access-grpc.log;
    location / {
        grpc_pass grpc://127.0.0.1:9091;
        grpc_set_header X-Real-IP $remote_addr;
    }
}
  1. get metadata from context in gRPC server side

    my golang code:

md, ok := metadata.FromIncomingContext(ctx)
...
md.Get("x-real-ip")
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM