Home > Enterprise >  API security questions in Django & React - Can Django validate if the userid in API == userid in Tok
API security questions in Django & React - Can Django validate if the userid in API == userid in Tok

Time:07-20

In Django's views.py I have the following code:

class MutatieView(viewsets.ModelViewSet):
# authentication_classes = (TokenAuthentication,)
authentication_classes = (JWTAuthentication,)
permission_classes = (IsAuthenticated,)
serializer_class = MutatieSerializer
queryset = Mutatie.objects.all()

def get_queryset(self, **kwargs):
    user_mutatie = Mutatie.objects.filter(userid=self.kwargs['userid'])
    return user_mutatie

In React a GET request is sent with the correct token in the header. But I commented out the original line (see below) and requested userid=1 instead of the userid as a variable of the current user which is 2.

export const apiSlice = createApi({
reducerPath: "api",
baseQuery: fetchBaseQuery({
    baseUrl: "http://127.0.0.1:8000/api/",
    prepareHeaders: (headers, { getState }) => {
        const access = (getState() as RootState).auth.access
        if (access) {
          headers.set('Authorization', `Bearer ${access}`);
        }
        return headers
      },
}),
tagTypes: ['MyMutatie',],
endpoints: (builder) => ({   
    ...
    myMutatieList: builder.query<IMutatie[], number>({
        query: (userid:number) => ({
            url: `mutaties/1/`,
            // url: `mutaties/${userid}/`,
        }),
    providesTags: ['MyMutatie']
    }),
    ...
}),       

});

Now I get user1's data as user2, which is a problem.

Django should be able to see in the token that the correct userid=2 and not 1. How to achieve such a validation?

Is the developer the only one to manipulate api calls like in the code above or are there other ways? In postman, but django only allows APIs from the given domain? Can that also be faked?

CodePudding user response:

You do not need to send the userid as URL parameter, the Django authentication middleware will resolve that for you. Use:

user_mutatie = Mutatie.objects.filter(userid=self.request.user.id)

For django only allows APIs from the given domain, you can add the domain in ALLOWED_HOSTS.

  • Related