Django REST Framework中的用户身份验证 [英] User Authentication in Django REST Framework

查看:333
本文介绍了Django REST Framework中的用户身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django REST后端,它有一个/users端点,可以在其中通过POST方法从前端添加新用户.

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

/users端点网址:

http://192.168.201.211:8024/users/

在此终结点计算机上,我可以查看所有用户信息并添加新用户,因此我必须避免其他用户(管理员除外)输入该信息.我用python manage.py createsuperuser用密码admin123创建一个超级用户admin.

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.

我的问题是,如果我想从前端执行HTTP POST(我使用Angular),我必须传递管理员的用户名和密码adminadmin123,以及POST头信息.因此,我让其他人知道检查前端源代码的用户名和密码.

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.

还有其他方法可以执行Authentication而不会将管理员的用户名和密码公开给其他人吗?

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

推荐答案

最后,我找到了解决此问题的方法.

Finally, I find a method to solve this problem.

这里有一种非常优雅的方法,可以在我的UserViewSet中重写get_queryset函数:

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

在变更1中,权限允许任何人访问,因此新用户无需任何身份验证即可执行POST.

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

在变更2中,我仅在用户为超级用户时才返回所有用户,就像重写get_queryset完成一样.

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

还需要更改urls.py文件以为此网址添加base_name,如下所示:

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

这篇关于Django REST Framework中的用户身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆