Client Authentication in Django rest framework powered App using django-oauth-toolkit

747 Views Asked by At

I am creating a project in django for my mobile app. The django project is the API backend for the mobile App. I have created a signup for the user model using django rest framework. The signup API works fine. Now, i want to let only the request from my mobile app to be served. For this i created an oauth application Authorization grant type " client-credentials "

class UserSerializer(ModelSerializer):
email = serializers.EmailField(
        required=True,
        validators=[UniqueValidator(queryset=User.objects.all())]
        )
username = serializers.CharField(
    validators=[UniqueValidator(queryset=User.objects.all())]
    )
password = serializers.CharField(min_length=8)

def create(self, validated_data):
    user = User.objects.create_user(validated_data['username'], validated_data['email'],
         validated_data['password'])
    return user

class Meta:
    model = User
    fields = ('id', 'username', 'email', 'password')
    read_only_fields = ('id',)
    write_only_fields = ('password',)

This is the user serializer and the view is

class UserCreateAPIView(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (IsAuthenticatedOrCreate, TokenHasScope)

But the problem is I can make direct calls to the signup api without using the toke. How to make sure that the User Create API is called when only the token is passed or the post request to be valid when the token is passed.

1

There are 1 best solutions below

1
On BEST ANSWER

You can simply create an application with grant type Client Credentials, and set your permission class as :

permission_classes = [TokenHasReadWriteScope]

For your other APIs, which require user authentication and authorization, you can issue another client with grant type Resource Owner Password Based, and set your permission class as :

permission_classes = [TokenHasReadWriteScope, YourCustomPermission]

Or, if you need both client credentials as well as resource owner password based (For eg, your signup api may need only client credentials but editing personal information of user may require resource owner password based grant). For this you can create custom application model and allow both for the client. http://django-oauth-toolkit.readthedocs.io/en/latest/advanced_topics.html?highlight=extending%20