【学習記録】Django REST frameworkチュートリアル12

この記事の続きです。

programming-gogogogo.hatenablog.com

こちらの動画を見ながらPythonDjango REST framework(DRF)について勉強しています。

www.youtube.com

今回はDRFでの認証について勉強します。
公式ドキュメントの説明はこちらです。

www.django-rest-framework.org

api_basic/views.pyでimportに以下を追加します。

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated 

次にGenericAPIViewクラスに以下の記述を追加します。

    authentication_classes = [SessionAuthentication, BasicAuthentication]

こちらを追加することでSessionAuthentication行い、それが認証されなかった場合はBasicAuthenticationを行うようです。
(ちゃんと理解できているか怪しいので要勉強)

次にpermission_classesも追加します。

    permission_classes = [IsAuthenticated]

GenericAPIViewクラスは以下のようになります。

class GenericAPIView(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin):
    serializer_class = ArticleSerializer
    queryset = Article.objects.all()

    lookup_field = 'id'

    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request, id=None):
        if id:
            return self.retrieve(request)
        else:
            return self.list(request)

    def post(self, request):
        return self.create(request)

    def put(self, request, id=None):
        return self.update(request, id)

    def delete(self, request, id):
        return self.destroy(request, id)

サーバーを再起動して、ログインしている状態でGETリクエストを送るとデータが取得できますが
f:id:JunpeiNakasone:20210324223052p:plain

管理画面からログアウトして
f:id:JunpeiNakasone:20210324223149p:plain

GenericAPIViewクラスにリクエスを送ると403Forbiddenエラーが出るようになり、認証が必要になっていることが確認できました。
f:id:JunpeiNakasone:20210324223317p:plain

Basic認証を通してデータを取得できることを確認するためにPostmanからGETリクエストでAuthorizationでBasic Authを選択し正しいユーザー名、パスワードを入力するとデータが取得できました。
f:id:JunpeiNakasone:20210324223830p:plain

基本的なBasic認証は動作確認できたので次回はDjangoのドキュメントで紹介されている認証機能を使っていきます。