ensminger
ensminger

Reputation: 711

How to allow access to App Engine from only specified IPs?

I am building a simple POST handler on GAE in Python that will accept a POST and write it to a Cloud SQL database.

I would like to limit access to this app to a limited number of IPs - non-GAE webservers where the POST originates. Essentially, how to allow POSTS from my IPs and disallow all other traffic?

Seems like a simple and common operation, but I haven't found a solution online that seems to fit. Most GAE authentication and routing packages are built around user auth.

Where should I look for a solution here? What Google keywords should I be using? Is this going to be written into the app itself or should I be focused on another component of GCP for IP access and routing?

Thanks!

Upvotes: 2

Views: 776

Answers (1)

ensminger
ensminger

Reputation: 711

All credit to Paul Collingwood for alerting me to the existence of request.remote_addr.

Here is my solution as of now:

ALLOWED_IP = ['173.47.xx.xx1', '173.47.xx.xx2']

class PostHandler(webapp2.RequestHandler):
def post(self):

    # Read the IP of the incoming request
    ip = self.request.remote_addr

    # If the IP is allowed, execute our code
    if ip in ALLOWED_IP:
        # Execute some awesome code

    # Otherwise, slam the door!
    else:
        self.error(403)

I'm not entirely sure that my self.error() usage is appropriate here, but this is working! POST requests made from the allowed IPs are accepted and executed. All others are given a 403.

I'm always eager to hear improvement suggestions.

Upvotes: 1

Related Questions