how can I securely perform Rest requests without authentication?

This is more a process logic question than a specific language-framework one.

I am developing a mobile app and want the user to be able to use it without having to login (i.e. try it and offer a plus to the logged users), but I don´t want other persons to make post requests from let´s say Postman or any other platform than the app without having some sort of key, so what would be the approach here?

I am thinking on basic auth with some secret username:password for guests, or some kind of token, but as I am totally new on this I am not sure if it´s the correct approach, I´ve read the authentication and permissions Django Rest Framework tutorial but haven´t found a solution

Upvotes: 0

Views: 43

Answers (1)

Joshua Blevins
Joshua Blevins

Reputation: 697

I am learning Django myself and have gotten to the more advanced topics in the subject. What you could do is create a function in your permissions.py file for this. like so:

from rest_framework import permissions

class specialMobileUserPermissions(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in request.SAFE_METHODS:
            return True

        if request.user.id == whatever your mobile users id is:
            return false

        return obj.id == request.user.id # if the user is a subscribed user and they are logged in return true

        return false # because we need a way out if none of the above works

So when dealing with permissions classes the permissions.SAFE_PERMISSIONS is a list of permissions that are non-destructive. So the first if statement asks are you a GET, HEAD, or other non data altering method. If so return true.

The second if statement checks the user id of the user that is making the request. And if that user id is equal to the user id you set for the mobile trail user it would return false, denying permissions to whatever this class is used on.

In your viewset you would need to add the permissions_classes variable like below

from . import permissions # your permissions.py file

class FooViewSet(viewsets.ViewSet):
    permission_classes = (permissions.specialMobileUserPermissions,)

Unless you need extra functionality, that should be everything you need, all the way down to the imports. I hope I have helped.

Upvotes: 1

Related Questions