简体   繁体   中英

How to use Django User Groups and Permissions on a React Frontend with Django Rest Framework

I am using Django Rest Framework with React on the Frontend. I am using Token Athentication and its all working fine. I now have a requirement of making sure different users can access different things depending on their rights. This is possible using Django admin but my users will be using the React frontend.

I looked through Django Rest permissions but I didnt see how I can use this on my React Frontend. I also looked at Django guardian but I am not sure if its what I need for my requirement. I have looked through many tutorials and articles but I can't seem to find any straight forward way to achieve this.

Here is the approach I have used sofar: Created a Serializer for the inbuilt User Model, then Created a ViewSet and I can now access the list of users through the api.

from django.contrib.auth.models import User

class UserSerializer(SerializerExtensionsMixin,serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

class UserViewSet(SerializerExtensionsAPIViewMixin, viewsets.ModelViewSet):
    serializer_class = UserSerializer
    queryset = User.objects.all()

router = DefaultRouter()
router.register(r'user', UserViewSet, basename='user')

Using this I am able to access a user with the groups and permissions as shown in the picture below. I am now going ahead to call the api url on my React frontend and somehow use the permissions and groups associated with the user to control what the users can see.

Is there a better way to achieve this requirement? Am I doing this the right way? Has someone done this and may be I can borrow from their experience?

在此处输入图片说明

DRF provides permission classes, Also if you need some customization you can do so by creating custom permission classes. Refer https://www.django-rest-framework.org/api-guide/permissions/#api-reference .

On React side if you are using React router you can guard each route on some roles /permissions received from backend. Refer https://hackernoon.com/role-based-authorization-in-react-c70bb7641db4 This might help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM