User Authentication in Django REST Framework

前端 未结 3 443
长发绾君心
长发绾君心 2021-01-26 02:55

I have a Django REST backend, and it has a /users endpoint where I can add new users through POST method from frontend.

/users end

相关标签:
3条回答
  • 2021-01-26 03:31

    token auth is may what you need,i use token auth for DRF as backend and angular as frontend

    0 讨论(0)
  • 2021-01-26 03:31

    Finally, I find a method to solve this problem.

    Here has a very elegant way to do this, rewrite get_queryset function in my UserViewSet:

    class UserViewSet(viewsets.ModelViewSet):
    
        # permission_classes = (permissions.IsAdminUser, )
        permission_classes = (permissions.AllowAny, )  # <-- change 1
        # queryset = User.objects.all()  # <-- change 2
        serializer_class = UserSerializer
    
        def get_queryset(self):
            queryset = User.objects.filter(id=self.request.user.id)
            if self.request.user.is_superuser:
                queryset = User.objects.all()
            return queryset
    

    In change 1, permissions allowed anyone to access, so a new user can do a POST without any authentication.

    In change 2, I only return all users when the user is superuser, just like rewrote get_queryset done.

    Also need to change urls.py file to add base_name for this url like this:

    router.register(r'users', UserViewSet, base_name='user')
    

    ref, https://stackoverflow.com/a/22767325/2803344

    0 讨论(0)
  • 2021-01-26 03:40

    You need to create an API that handles the user creation. This is why we create backends. The user will send the API their credentials and the API will add the user to the database using the admin credentials and post request. The API's code will not be viewable. Depending on your needs, auth0 can be a good solution and save you time on user registration and login. If you make your own sign up and login be sure to hash passwords and make sure they are sent over SSL. A service like auth0 will handle all this for you if you want to focus on other parts of your project.

    0 讨论(0)
提交回复
热议问题