User Authentication in Django REST Framework

2019-03-06 12:51发布

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

/users endpoint url:

http://192.168.201.211:8024/users/

In this endpoint I can view all users information and add new user, so I must avoid others entry it except Administrator. I create a superuser admin with password admin123 by python manage.py createsuperuser.

My question is, If I want to do a HTTP POST from frontend(I use Angular) I have to pass the Administrator's user name and password, admin and admin123, along with POST head information. So I let others know the user name and password who check the source code of frontend.

Is there any other way to do this Authentication without exposing Administrator's user name and password to others?

3条回答
forever°为你锁心
2楼-- · 2019-03-06 13:03

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-03-06 13:13

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

查看更多
狗以群分
4楼-- · 2019-03-06 13:26

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

查看更多
登录 后发表回答