2011-08-31 7 views
8

私は比較的新しいDjangoとそのエコシステムです。私はdjango-tastypieを使用してモバイルクライアントのREST APIを書いています。私はRESTインターフェイスを作成するためのtastypieの使い方について、ほとんどすべてのWeb上のサンプルを見てきました。クライアントからのデータのポストに特有のものではなく、どのようにしてクライアントを認可するのでしょうか。は、django-tastypieを使用して許可を行う例が必要です

この例では、tastypie.authentication.BasicAuthenticationを使用しました。それはユーザー名とパスワードを要求するポップアップを開き、ブラウザ上で正常に動作します。しかし、モバイルで同じことをするかどうかはわかりません(具体的には、ネイティブIOSアプリケーション)。ユーザーがブラウザを使わずにネイティブアプリを使用している場合に、このポップアップが自分の携帯端末に表示される方法をログイン要求するときは、あまり得意ではありません。

私はこれで完全に失われています。私は本当にあなたの助けに感謝します。

+0

これは、実際には、ジャンゴとタスティピーの特有のものではありません。 POSTリクエストを行っているライブラリがリクエストに応じてユーザ名/パスワードの記入をサポートしているかどうかを確認する必要があります。 –

+0

質問はAUTHORIZATIONであり、AUTHORIZATIONではありません。 – Yefei

答えて

0

感謝。

@Iuriiで言及された同様のアプローチを使用しました。ここに私の解決策があります。

私は認証を処理するためのクラスを作成し、is_authenticatedメソッドをオーバーライドしました。私はtastypieリソースクラスのメタ定義でこのクラスを使うことができます。

 

    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() 

これにより、リソースへのアクセス要求が認証コードを確実に通過するようになります。

+0

以下のコメントのサンプルコードを添付してください。 ここでは、ユーザー名とパスワードを要求するオブジェクトを確認するロジックを入力します。ユーザーが認証されている場合はTrueを返し、それ以外の場合はFalseを返します。 – sumit

+0

@ timus2001確かに、 。 [サンプルコード](http://pastebin.com/R0RnuFJs) – sanket

2

ソースをチェックアウトして、ApiKeyAuthenticationなどを使用できます。 認証ユーザーには、POSTユーザー名とAPIキーが必要です。

iosアプリで使用可能なようです。 ここにチェックコードの一部があります。助けのための

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

関連する問題