Home > Net >  django REST framework - allow only list of IP addresses to access?
django REST framework - allow only list of IP addresses to access?

Time:09-26

I am trying to figure out the correct way to limit access to an API endpoint using IP address. I went through the docs, blocking is mentioned but limiting the call to API endpoint is not.

What is the correct way to do this?

CodePudding user response:

Depending of your server architecture you can achieve it clearly programmatically, by:

def retrieve_user_ip(request):
    user_ip = request.META.get('HTTP_X_FORWARDED_FOR')
    if user_ip:
        ip = user_ip.split(',')[-1] # According to Wiki, have to grab last element from HTTP_X_FORWARDED_FOR header
    else:
        ip = request.META.get('REMOTE_ADDR') # Basing on Django docs https://docs.djangoproject.com/en/4.0/ref/request-response/#django.http.HttpRequest.META
    return ip

CodePudding user response:

You can make a custom permission to check if the ip address is in the list of safe ip addresses and set it in the DEFAULT_PERMISSION_CLASSES.

Something like:

class SafeIPPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        if ip := request.META.get('HTTP_X_FORWARDED_FOR'):
            ip = ip.split(',')[-1]r
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip IN settings.SAFE_IPS

And in your settings:

SAFE_IPS = [
    127.0.0.1,
    10.0.0.1,
    ...
]

...

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        ...
        'path.to.custom.permissions.SafeIPPermission',
        ...
    ]
}
  • Related