Junely
Junely

Reputation: 21

How to POST a data into the restricted REST API url without logging in as a user?

In my Django app. I use django.contrib.auth as authentication for users, I also have django rest framework APIs.

I have enabled.

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),

@views.py under /api/data/

class TestView(generics.ListCreateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = TestSerializer
    queryset = Test.objects.all()
    filterset_class = TestFilter

    def get(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = TestSerializer(queryset, many=True)
        return Response(serializer.data)

Since, I can only access the API data by logging in through the user account, but on my project. I have a sensor(IoT) that have to POST into the api 127.0.0.1/api/data/,

How can I authenticate my sensor(IoT) to POST request into the API url without expiring session?

or

How to POST a data into the restricted REST API url without logging in as a user?

Thanks!

Upvotes: 0

Views: 770

Answers (1)

Radwan Abu-Odeh
Radwan Abu-Odeh

Reputation: 2045

For such cases, when you need a token for clients that can't refresh their session/token regularly, you can always go with Token Authentication (In which each user has a non-expired token to use.)

There is an existing solution within DjangoRestFramework, use Token Authentication Backend, you can also use it next to your existing Authentication Backends.

Upvotes: 1

Related Questions