Obtain user IP address in python middleware

Hi, I am trying to obtain the IP address of the sender in the Tyk middleware using python. I read up on the request context variables here which mentioned that the header ‘x-remote-addr’ would be available.

However, in the python middleware code, I tried printing out the headers in the def PostKeyAuth(request, session, spec) hook using tyk.log("Request: " + str(request.dict), “info”) but could not find that header. Is there anything I missed?

Hi @salEugene

I was able to get this to work, so it’s possible. We just have to work out exactly the issue you’re having.

This is my simple python code

from tyk.decorators import *
from gateway import TykGateway as tyk

@Hook
def Headers(request, session, spec):
        logLevel = "info"
        tyk.log("Headers START", logLevel)
        for key in request.object.headers:
                tyk.log("Header: " + key + " is " + request.object.headers[key], logLevel)
        tyk.log("Headers END", logLevel)
        return request, session

It gives this sort of thing in my gateway logs

time="Jan 13 11:57:05" level=info msg="Headers START" prefix=python
time="Jan 13 11:57:05" level=info msg="Header: Host is localhost:8080" prefix=python
time="Jan 13 11:57:05" level=info msg="Header: User-Agent is curl/7.29.0" prefix=python
time="Jan 13 11:57:05" level=info msg="Header: Accept is */*" prefix=python
time="Jan 13 11:57:05" level=info msg="Header: X-Remote-Addr is 127.0.0.1" prefix=python
time="Jan 13 11:57:05" level=info msg="Headers END" prefix=python

The fist thing to check that that X-Remote-Addr is being populated. For this I pointed my API at http:/httpbin.org/get and checked it’s reply.

Assuming you’re seeing X-Remote-Addr populated, the next thing to check is that you’re calling your python plugin late enough in the middleware sequence to make sure tyk has populated the header.

Request Middleware Chain gives a nice diagram of when different things happen as the request makes its way through the gateway. I’ve put my plugin in the ‘post’ section.

Here’s my manifest for reference

{
  "file_list": [
    "headers.py"
  ],
  "custom_middleware": {
    "driver": "python",
    "post": [
    {
      "name": "Headers"
    }
    ]
  }
}

If you’re still having trouble. Please let us know what version of the gateway you are trying (I’m using 3.0.9 which is the current long term support) and also please upload your API definition so we can have a look at that too.

Cheers,
Pete