User Authentication in Django REST Framework

I have a Django REST backend and it has a /users endpoint where I can add new users using the POST method from the interface.

/users endpoint url:

http://192.168.201.211:8024/users/

At this endpoint, I can view all the user information and add a new user, so I should avoid entries other than the Administrator. I am creating admin superuser with password admin123 on python manage.py createsuperuser .

My question is: if I want to use HTTP POST from the frontend (I use Angular), I have to pass the administrator username and password, admin and admin123 , as well as POST head information. Therefore, I let others know the username and password that verify the source code of the interface.

Is there another way to do this Authentication without calling the username and password of the administrator to other users?

0
rest django angular
source share
3 answers

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

0
source share

auth token can what you need, i use auth token for DRF as backend and angular as interface

0
source share

Finally, I found a way to solve this problem.

Here's a very elegant way to do this, by rewriting the 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 someone to access, so a new user can perform POST without any authentication.

In change 2, I return all users only when the user is superuser, as rewritten by get_queryset done.

You also need to modify the urls.py file to add the base_name for this URL, for example:

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

ref, stack overflow

0
source share

All Articles