Django-React authentication: limit users who can obtain simpleJWT tokens

Viewed 384

I have two React frontends for my backend: the first one is used by all users, the second one is an admin panel that can only be used by is_staff users.

What is the best way to limit access using simplejwt tokens?

I have overridden TokenObtainPairSerializer to include additional fields like 'is_staff'.

So I have two questions:

  1. is just checking the is_staff field on the frontend safe enough? Doesn't seem to me like a good idea.

  2. if I want to create a second API URL entry for admin authentication and override authentication logic on the backend side to only issue tokens to staff users. What method/class exactly should I override to change this? Is this a good idea?

3 Answers

The is_staff flag can be used for visual checks on the frontend, but views restricted to users with such permissions must be protected on the backend.

Assuming that you are using the Django Rest Framekwork, the best way of protecting your views is to use permissions, or more precisely, custom permissions.

from rest_framework import permissions

class IsStaffUser(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.is_staff

and them

from rest_framework.permissions import IsStaffUser

class StaffViewModelViewSet(viewsets.ModelViewSet):
    permission_classes = (IsStaffUser,)

more content about that can be found on:

Django Rest Framework Staff Only Permissions

Django Rest Framework Custom Permissions Per View

Django Rest Framework Permissions

Create Permission classes for django views to give access to them for users that are allowed and disallow users that are not allowed.

For example, your current logic states that is_staff users should only be allowed to login to Admin portal. It can be done easily by simply adding a permission class which allowes or disallows user to login to your admin portal. If you are using single JWTAPI for both, you should use a middleware on this API to detect where the data came from as _requests.META contains this data. You can detect if user is allowed all in backend using this META data.

encode is_staff in jwToken and when the user send a request with jwToken, decode it in the backend and check if is_staff user then based on this attribute you can do what you ever want.

Related