LoginSignup
1
0

More than 1 year has passed since last update.

Google Cloud Functions(Python) でIP制限を行う

Posted at

背景

Google Cloud FunctionsでIP制限を行いたい。
VPCSCやCloud Load Balancer経由のアクセスにすることによってIP制限を行う方法があるが、少し面倒。
今回はシンプルにpythonコードでIP制御をすることにした。

実装

Google Cloud FuntionsのPythonはFlaskで実装されている。
Flaskのリクエスト元アドレスは request.remote_addr で取得できる。

import ipaddress

def ip_allowed(ip):
    ip = ipaddress.ip_address(ip)
    nw = ipaddress.ip_network(ip_range)
    return (ip in nw)


def main(request):
    if not ip_allowed(request.remote_addr):
        raise Exception(f"IP not allowed: {request.remote_addr}")
    return 'IP allowed.'

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0