Need an example authorization using django-tastypie

I am relatively new to Django and its ecosystem. I am writing a REST api for our mobile client using django-tastypie. I looked through almost all the examples on the Internet about how to use tastypie to create REST interfaces. but none of them is specific to POSTing data from the client and how you authorize the client.

I used from tastypie.authentication.BasicAuthentication as shown in the example. It opens a popup asking for a username and password and works fine in the browser. But I'm not sure if he will do the same on mobile devices (in particular, on his native iOS application). I don’t quite understand when a user makes a login request, how this pop-up window will be shown on his mobile device if he or she does not use a browser, but a native application.

I completely lost this, I would really appreciate your help.

+8
django tastypie
source share
2 answers

Thanks for the help.

I used a similar approach mentioned by @Iurii. Here is my solution.

I wrote a class to handle authentication and overriding the is_authenticated method. and then I can use this class in the meta definition of tastypie resource classes.

     from tastypie.authentication import BasicAuthentication
     from tastypie.resources import Resource, ModelResource

     # class for handling authentication
     class MyAuthentication (BasicAuthentication):
         def is_authenticated (self, request, ** kwargs):
             # put here the logic to check username and password from request object
             # if the user is authenticated then return True otherwise return False

     # tastypie resource class
     class MyResource (ModelResource):
         class Meta:
             authentication = MyAuthentication ()

this will ensure that the request for access to the resource goes through your authentication code.

0
source share

You can check the source and use, for example, ApiKeyAuthentication. You just need to specify the POST username and api key to authenticate the user.

It is similar to the ios app for iOS. Here is part of the verification code.

def is_authenticated(self, request, **kwargs): """ Finds the user and checks their API key. Should return either ``True`` if allowed, ``False`` if not or an ``HttpResponse`` if you need something custom. """ from django.contrib.auth.models import User username = request.GET.get('username') or request.POST.get('username') api_key = request.GET.get('api_key') or request.POST.get('api_key') if not username or not api_key: return self._unauthorized() try: user = User.objects.get(username=username) except (User.DoesNotExist, User.MultipleObjectsReturned): return self._unauthorized() request.user = user return self.get_key(user, api_key) 

https://github.com/toastdriven/django-tastypie/blob/master/tastypie/authentication.py#L128 https://github.com/toastdriven/django-tastypie/blob/master/tastypie/authorization.py#L42

+2
source share

All Articles