Role Based Access Control for different API methods in Django REST Framework

392 views
Skip to first unread message

Azar Mohamed

unread,
Sep 7, 2019, 11:38:38 AM9/7/19
to Django users
I am creating REST API for Product, which has following Permission, (create_product, view_product, edit_product). In my Project I am having various users with different roles (Ex: Producer, Retailer, Consumer,...etc). I am assigning permission to individual Roles. I am using Django Group Permission

Example: The "Producer" role has "create_product" and "view_product" permission. The "Retailer" role has "edit_product" permission. The "Consumer" role has no permission.

I want to restrict the Access based on the permission code. I need a generic approach to solve this. I want to use the same approach for different views with different permission codes.

In my view.py,

class Product(viewsets.ModelViewSet):

serializer_class = ProductSerializer
queryset = Product.objects.all()

In settings.py, I have added following code.

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
}

gulo loki

unread,
Sep 7, 2019, 1:35:53 PM9/7/19
to django...@googlegroups.com
in your viewset class,you could  rewrite   get_permissions to set which permissions you want on action
    def get_permissions(self, *args, **kwargs):
        if self.action == 'create':
            self.permission_classes = (AllowAny,)
        elif self .action == 'login':
            self.permission_classes = (AllowAny,)

Azar Mohamed <azarm...@gmail.com> 于2019年9月7日周六 下午11:37写道:
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b67aed04-a096-4c1d-a453-b0be1274dc83%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages