Django REST Framework中的用户身份验证 [英] User Authentication in 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),我必须传递管理员的用户名和密码admin
和admin123
,以及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屋!