jpadilla / django-rest-framework-jwt

JSON Web Token Authentication support for Django REST Framework
http://jpadilla.github.io/django-rest-framework-jwt/
MIT License
3.19k stars 648 forks source link

Possibility to allow connection without token #446

Closed pinkynrg closed 6 years ago

pinkynrg commented 6 years ago

I would like to allow connections without the need of a token when requests come from the same machine.

In short I have a local service on the same machine of the web application and in order to avoid overhead I would like to let the service communicate without the need of authentication when the api call comes from 127.0.0.1.

Does anyone have a straightforward way to do it? Is it a good idea?

pinkynrg commented 6 years ago

solved by doing this:

from rest_framework.permissions import BasePermission

class IsAuthenticated(BasePermission):
    """
    Allows access only to authenticated users.
    """

    def get_client_ip(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

    def has_permission(self, request, view):
        return self.get_client_ip(request) == '127.0.0.1' or (request.user and request.user.is_authenticated)