TheChosenOne
TheChosenOne

Reputation: 105

Is there a way to read IP connection header inside server application in go?

Server application supports authentication which demands username and password from the client who is connecting with it. There can be a client from within the machine as well for which I do not want it to be authenticated. Client within the same machine connects with the server with the LOOPBACK address. What I want is that, if I can somehow apply filter for the destination IP of the gRPC connection and decide whether to apply authentication or not. Is there a way? Thanks !

func (s *RShellServer) ExecCmd(stream RShell_ExecCmdServer) error {
    # For example, something like this if condition.
    if (Conn().destination_ip != LOOPBACK) {
        if err, ok := gnmi.AuthorizeUser(stream.Context()); !ok {
                return fmt.Errorf("%s", err)
        }
    }
    req, err := stream.Recv()
    if err != nil {
        return fmt.Errorf("Error reading request: %s", err)
    }
}

Upvotes: 3

Views: 872

Answers (1)

Shubham Srivastava
Shubham Srivastava

Reputation: 1877

Your GRPC service should be something like this

func (MyServer) SomeFunction(ctx context.Context, 
    req *myserver.Request) (resp *myserver.Response, err error)

Then you can use peer library and extract peer information from context like `

p, err := peer.FromContext(ctx)

And get address from peer using

p.Addr

Upvotes: 2

Related Questions