1

how to change permissions for current view overriding the DEFAULT_PERMISSION_CLASSES in django rest-framework

Here is how i set my defaultpermissions in my settings.py :

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',  # <-- And here
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}

and i need to use AllowAny on the signUp method :

@permission_classes([AllowAny,])
@api_view(["POST", ])
def add_new_user(request):
    if request.method == "POST":
        lang = request.data["lang"]
..........
.........
.......

Still, it returns Authentication credentials were not provided. .. I mainly need to have permissions with a token with every request but not the register and login request. how to do it ??

Ahmed Wagdi
  • 3,913
  • 10
  • 50
  • 116
  • based on drf docs default permission must be overridden when use the decorator.. check your code with doc example https://www.django-rest-framework.org/api-guide/permissions/ – Reza Heydari Jul 05 '21 at 15:19
  • `Note: when you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in the settings.py file.` that is what they say and that is how it should work but it not . – Ahmed Wagdi Jul 05 '21 at 15:22
  • I guess the order of decorators is important – Reza Heydari Jul 05 '21 at 15:52

2 Answers2

1

A Way to do that is using Object Level Permissions in Django. You just setup as normally in settings.py and add manually a permission into every class view. For me is the best way to do it. Normally will be Views witch is are Admin only, Authenticated or just Open.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication', 
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoObjectPermissions',#Object Level Permission
        
    ]
}

After set this line into your settings.py just follow adding a permission_classes into view. Like:

class LoginUser(APIView):
    permission_classes = [AllowAny, ]
    ...

References

DjangoObjectPermissions

Django Class Based Views

0

Here is how I solved this :

in my settings.py i added both permissions classes

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',  # <-- And here
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',  #both are mentioned 
        'rest_framework.permissions.AllowAny',
    ]
}

and in my view, I had to move the permission dictator to be the last thing before the view itself.

@api_view(["POST", ])
@permission_classes([AllowAny])
def login_user(request):
    if request.method == "POST":
        lang = request.data["lang"]
...
Ahmed Wagdi
  • 3,913
  • 10
  • 50
  • 116